Remove some miscellaneous references to SSL_CONNECTION
[openssl.git] / ssl / record / methods / tls_common.c
1 /*
2  * Copyright 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 <assert.h>
11 #include <openssl/bio.h>
12 #include <openssl/ssl.h>
13 #include <openssl/err.h>
14 #include <openssl/core_names.h>
15 #include "internal/e_os.h"
16 #include "internal/packet.h"
17 #include "../../ssl_local.h"
18 #include "../record_local.h"
19 #include "recmethod_local.h"
20
21 static void tls_int_free(OSSL_RECORD_LAYER *rl);
22
23 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
24                        const char *fmt, ...)
25 {
26     va_list args;
27
28     va_start(args, fmt);
29     ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
30     va_end(args);
31
32     rl->alert = al;
33 }
34
35 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
36                                      EVP_CIPHER_CTX *ctx,
37                                      const EVP_CIPHER *ciph,
38                                      const EVP_MD *md)
39 {
40     /*
41      * Provided cipher, the TLS padding/MAC removal is performed provider
42      * side so we need to tell the ctx about our TLS version and mac size
43      */
44     OSSL_PARAM params[3], *pprm = params;
45     size_t macsize = 0;
46     int imacsize = -1;
47
48     if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
49             && !rl->use_etm)
50         imacsize = EVP_MD_get_size(md);
51     if (imacsize >= 0)
52         macsize = (size_t)imacsize;
53
54     *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
55                                        &rl->version);
56     *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
57                                           &macsize);
58     *pprm = OSSL_PARAM_construct_end();
59
60     if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
61         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
62         return 0;
63     }
64
65     return 1;
66 }
67
68 /*
69  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
70  * which ssl3_cbc_digest_record supports.
71  */
72 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
73 {
74     switch (EVP_MD_CTX_get_type(ctx)) {
75     case NID_md5:
76     case NID_sha1:
77     case NID_sha224:
78     case NID_sha256:
79     case NID_sha384:
80     case NID_sha512:
81         return 1;
82     default:
83         return 0;
84     }
85 }
86
87 #ifndef OPENSSL_NO_COMP
88 static int tls_allow_compression(OSSL_RECORD_LAYER *rl)
89 {
90     if (rl->options & SSL_OP_NO_COMPRESSION)
91         return 0;
92
93     return rl->security == NULL
94            || rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
95 }
96 #endif
97
98 static int tls_setup_write_buffer(OSSL_RECORD_LAYER *rl, size_t numwpipes,
99                                   size_t len)
100 {
101     unsigned char *p;
102     size_t align = 0, headerlen;
103     SSL3_BUFFER *wb;
104     size_t currpipe;
105     SSL_CONNECTION *s = (SSL_CONNECTION *)rl->cbarg;
106
107     rl->numwpipes = numwpipes;
108
109     if (len == 0) {
110         if (SSL_CONNECTION_IS_DTLS(s))
111             headerlen = DTLS1_RT_HEADER_LENGTH + 1;
112         else
113             headerlen = SSL3_RT_HEADER_LENGTH;
114
115 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
116         align = SSL3_ALIGN_PAYLOAD - 1;
117 #endif
118
119         len = ssl_get_max_send_fragment(s)
120             + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
121 #ifndef OPENSSL_NO_COMP
122         if (ssl_allow_compression(s))
123             len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
124 #endif
125         if (!(rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS))
126             len += headerlen + align + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD;
127     }
128
129     wb = rl->wbuf;
130     for (currpipe = 0; currpipe < numwpipes; currpipe++) {
131         SSL3_BUFFER *thiswb = &wb[currpipe];
132
133         if (thiswb->len != len) {
134             OPENSSL_free(thiswb->buf);
135             thiswb->buf = NULL;         /* force reallocation */
136         }
137
138         if (thiswb->buf == NULL) {
139             if (s->wbio == NULL || !BIO_get_ktls_send(s->wbio)) {
140                 p = OPENSSL_malloc(len);
141                 if (p == NULL) {
142                     rl->numwpipes = currpipe;
143                     /*
144                      * We've got a malloc failure, and we're still initialising
145                      * buffers. We assume we're so doomed that we won't even be able
146                      * to send an alert.
147                      */
148                     SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
149                     return 0;
150                 }
151             } else {
152                 p = NULL;
153             }
154             memset(thiswb, 0, sizeof(SSL3_BUFFER));
155             thiswb->buf = p;
156             thiswb->len = len;
157         }
158     }
159
160     return 1;
161 }
162
163 static void tls_release_write_buffer(OSSL_RECORD_LAYER *rl)
164 {
165     SSL3_BUFFER *wb;
166     size_t pipes;
167
168     pipes = rl->numwpipes;
169
170     while (pipes > 0) {
171         wb = &rl->wbuf[pipes - 1];
172
173         if (SSL3_BUFFER_is_app_buffer(wb))
174             SSL3_BUFFER_set_app_buffer(wb, 0);
175         else
176             OPENSSL_free(wb->buf);
177         wb->buf = NULL;
178         pipes--;
179     }
180
181     rl->numwpipes = 0;
182 }
183
184 int tls_setup_read_buffer(OSSL_RECORD_LAYER *rl)
185 {
186     unsigned char *p;
187     size_t len, align = 0, headerlen;
188     SSL3_BUFFER *b;
189
190     b = &rl->rbuf;
191
192     if (rl->isdtls)
193         headerlen = DTLS1_RT_HEADER_LENGTH;
194     else
195         headerlen = SSL3_RT_HEADER_LENGTH;
196
197 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
198     align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
199 #endif
200
201     if (b->buf == NULL) {
202         len = SSL3_RT_MAX_PLAIN_LENGTH
203             + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
204 #ifndef OPENSSL_NO_COMP
205         if (tls_allow_compression(rl))
206             len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
207 #endif
208         if (b->default_len > len)
209             len = b->default_len;
210         if ((p = OPENSSL_malloc(len)) == NULL) {
211             /*
212              * We've got a malloc failure, and we're still initialising buffers.
213              * We assume we're so doomed that we won't even be able to send an
214              * alert.
215              */
216             RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
217             return 0;
218         }
219         b->buf = p;
220         b->len = len;
221     }
222
223     return 1;
224 }
225
226 static int tls_release_read_buffer(OSSL_RECORD_LAYER *rl)
227 {
228     SSL3_BUFFER *b;
229
230     b = &rl->rbuf;
231     if ((rl->options & SSL_OP_CLEANSE_PLAINTEXT) != 0)
232         OPENSSL_cleanse(b->buf, b->len);
233     OPENSSL_free(b->buf);
234     b->buf = NULL;
235     return 1;
236 }
237
238 /*
239  * Return values are as per SSL_read()
240  */
241 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
242                        int clearold, size_t *readbytes)
243 {
244     /*
245      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
246      * packet by another n bytes. The packet will be in the sub-array of
247      * rl->rbuf.buf specified by rl->packet and rl->packet_length. (If
248      * rl->read_ahead is set, 'max' bytes may be stored in rbuf [plus
249      * rl->packet_length bytes if extend == 1].) if clearold == 1, move the
250      * packet to the start of the buffer; if clearold == 0 then leave any old
251      * packets where they were
252      */
253     size_t len, left, align = 0;
254     unsigned char *pkt;
255     SSL3_BUFFER *rb;
256
257     if (n == 0)
258         return OSSL_RECORD_RETURN_NON_FATAL_ERR;
259
260     rb = &rl->rbuf;
261     left = rb->left;
262 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
263     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
264     align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
265 #endif
266
267     if (!extend) {
268         /* start with empty packet ... */
269         if (left == 0) {
270             rb->offset = align;
271         } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
272             /*
273              * check if next packet length is large enough to justify payload
274              * alignment...
275              */
276             pkt = rb->buf + rb->offset;
277             if (pkt[0] == SSL3_RT_APPLICATION_DATA
278                     && (pkt[3] << 8 | pkt[4]) >= 128) {
279                 /*
280                  * Note that even if packet is corrupted and its length field
281                  * is insane, we can only be led to wrong decision about
282                  * whether memmove will occur or not. Header values has no
283                  * effect on memmove arguments and therefore no buffer
284                  * overrun can be triggered.
285                  */
286                 memmove(rb->buf + align, pkt, left);
287                 rb->offset = align;
288             }
289         }
290         rl->packet = rb->buf + rb->offset;
291         rl->packet_length = 0;
292         /* ... now we can act as if 'extend' was set */
293     }
294
295     len = rl->packet_length;
296     pkt = rb->buf + align;
297     /*
298      * Move any available bytes to front of buffer: 'len' bytes already
299      * pointed to by 'packet', 'left' extra ones at the end
300      */
301     if (rl->packet != pkt && clearold == 1) {
302         memmove(pkt, rl->packet, len + left);
303         rl->packet = pkt;
304         rb->offset = len + align;
305     }
306
307     /*
308      * For DTLS/UDP reads should not span multiple packets because the read
309      * operation returns the whole packet at once (as long as it fits into
310      * the buffer).
311      */
312     if (rl->isdtls) {
313         if (left == 0 && extend)
314             return 0;
315         if (left > 0 && n > left)
316             n = left;
317     }
318
319     /* if there is enough in the buffer from a previous read, take some */
320     if (left >= n) {
321         rl->packet_length += n;
322         rb->left = left - n;
323         rb->offset += n;
324         *readbytes = n;
325         return OSSL_RECORD_RETURN_SUCCESS;
326     }
327
328     /* else we need to read more data */
329
330     if (n > rb->len - rb->offset) {
331         /* does not happen */
332         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
333         return OSSL_RECORD_RETURN_FATAL;
334     }
335
336     /* We always act like read_ahead is set for DTLS */
337     if (!rl->read_ahead && !rl->isdtls) {
338         /* ignore max parameter */
339         max = n;
340     } else {
341         if (max < n)
342             max = n;
343         if (max > rb->len - rb->offset)
344             max = rb->len - rb->offset;
345     }
346
347     while (left < n) {
348         size_t bioread = 0;
349         int ret;
350         BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
351
352         /*
353          * Now we have len+left bytes at the front of rl->rbuf.buf and
354          * need to read in more until we have len + n (up to len + max if
355          * possible)
356          */
357
358         clear_sys_error();
359         if (bio != NULL) {
360             ret = BIO_read(bio, pkt + len + left, max - left);
361             if (ret > 0) {
362                 bioread = ret;
363                 ret = OSSL_RECORD_RETURN_SUCCESS;
364             } else if (BIO_should_retry(bio)) {
365                 if (rl->prev != NULL) {
366                     /*
367                      * We were reading from the previous epoch. Now there is no
368                      * more data, so swap to the actual transport BIO
369                      */
370                     BIO_free(rl->prev);
371                     rl->prev = NULL;
372                     continue;
373                 }
374                 ret = OSSL_RECORD_RETURN_RETRY;
375             } else if (BIO_eof(bio)) {
376                 ret = OSSL_RECORD_RETURN_EOF;
377             } else {
378                 ret = OSSL_RECORD_RETURN_FATAL;
379             }
380         } else {
381             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
382             ret = OSSL_RECORD_RETURN_FATAL;
383         }
384
385         if (ret <= OSSL_RECORD_RETURN_RETRY) {
386             rb->left = left;
387             if ((rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0 && !rl->isdtls)
388                 if (len + left == 0)
389                     tls_release_read_buffer(rl);
390             return ret;
391         }
392         left += bioread;
393         /*
394          * reads should *never* span multiple packets for DTLS because the
395          * underlying transport protocol is message oriented as opposed to
396          * byte oriented as in the TLS case.
397          */
398         if (rl->isdtls) {
399             if (n > left)
400                 n = left;       /* makes the while condition false */
401         }
402     }
403
404     /* done reading, now the book-keeping */
405     rb->offset += n;
406     rb->left = left - n;
407     rl->packet_length += n;
408     *readbytes = n;
409     return OSSL_RECORD_RETURN_SUCCESS;
410 }
411
412 /*
413  * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
414  * for us in the buffer.
415  */
416 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
417 {
418     SSL3_BUFFER *rbuf;
419     size_t left, len;
420     unsigned char *p;
421
422     rbuf = &rl->rbuf;
423
424     p = SSL3_BUFFER_get_buf(rbuf);
425     if (p == NULL)
426         return 0;
427
428     left = SSL3_BUFFER_get_left(rbuf);
429
430     if (left < SSL3_RT_HEADER_LENGTH)
431         return 0;
432
433     p += SSL3_BUFFER_get_offset(rbuf);
434
435     /*
436      * We only check the type and record length, we will sanity check version
437      * etc later
438      */
439     if (*p != SSL3_RT_APPLICATION_DATA)
440         return 0;
441
442     p += 3;
443     n2s(p, len);
444
445     if (left < SSL3_RT_HEADER_LENGTH + len)
446         return 0;
447
448     return 1;
449 }
450
451 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
452                                       size_t overhead, int send)
453 {
454     uint32_t max_early_data = rl->max_early_data;
455
456     if (max_early_data == 0) {
457         RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
458                     SSL_R_TOO_MUCH_EARLY_DATA);
459         return 0;
460     }
461
462     /* If we are dealing with ciphertext we need to allow for the overhead */
463     max_early_data += overhead;
464
465     if (rl->early_data_count + length > max_early_data) {
466         RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
467                     SSL_R_TOO_MUCH_EARLY_DATA);
468         return 0;
469     }
470     rl->early_data_count += length;
471
472     return 1;
473 }
474
475 /*
476  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
477  * will be processed per call to tls_get_more_records. Without this limit an
478  * attacker could send empty records at a faster rate than we can process and
479  * cause tls_get_more_records to loop forever.
480  */
481 #define MAX_EMPTY_RECORDS 32
482
483 #define SSL2_RT_HEADER_LENGTH   2
484
485 /*-
486  * Call this to buffer new input records in rl->rrec.
487  * It will return a OSSL_RECORD_RETURN_* value.
488  * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
489  * records have been decoded. For each record 'i':
490  * rrec[i].type    - is the type of record
491  * rrec[i].data,   - data
492  * rrec[i].length, - number of bytes
493  * Multiple records will only be returned if the record types are all
494  * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
495  * |max_pipelines|
496  */
497 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
498 {
499     int enc_err, rret;
500     int i;
501     size_t more, n;
502     SSL3_RECORD *rr, *thisrr;
503     SSL3_BUFFER *rbuf;
504     unsigned char *p;
505     unsigned char md[EVP_MAX_MD_SIZE];
506     unsigned int version;
507     size_t mac_size = 0;
508     int imac_size;
509     size_t num_recs = 0, max_recs, j;
510     PACKET pkt, sslv2pkt;
511     SSL_MAC_BUF *macbufs = NULL;
512     int ret = OSSL_RECORD_RETURN_FATAL;
513
514     rr = rl->rrec;
515     rbuf = &rl->rbuf;
516     if (rbuf->buf == NULL) {
517         if (!tls_setup_read_buffer(rl)) {
518             /* RLAYERfatal() already called */
519             return OSSL_RECORD_RETURN_FATAL;
520         }
521     }
522
523     max_recs = rl->max_pipelines;
524
525     if (max_recs == 0)
526         max_recs = 1;
527
528     do {
529         thisrr = &rr[num_recs];
530
531         /* check if we have the header */
532         if ((rl->rstate != SSL_ST_READ_BODY) ||
533             (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
534             size_t sslv2len;
535             unsigned int type;
536
537             rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
538                                      SSL3_BUFFER_get_len(rbuf), 0,
539                                      num_recs == 0 ? 1 : 0, &n);
540
541             if (rret < OSSL_RECORD_RETURN_SUCCESS)
542                 return rret; /* error or non-blocking */
543
544             rl->rstate = SSL_ST_READ_BODY;
545
546             p = rl->packet;
547             if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
548                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
549                 return OSSL_RECORD_RETURN_FATAL;
550             }
551             sslv2pkt = pkt;
552             if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
553                     || !PACKET_get_1(&sslv2pkt, &type)) {
554                 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
555                 return OSSL_RECORD_RETURN_FATAL;
556             }
557             /*
558              * The first record received by the server may be a V2ClientHello.
559              */
560             if (rl->role == OSSL_RECORD_ROLE_SERVER
561                     && rl->is_first_record
562                     && (sslv2len & 0x8000) != 0
563                     && (type == SSL2_MT_CLIENT_HELLO)) {
564                 /*
565                  *  SSLv2 style record
566                  *
567                  * |num_recs| here will actually always be 0 because
568                  * |num_recs > 0| only ever occurs when we are processing
569                  * multiple app data records - which we know isn't the case here
570                  * because it is an SSLv2ClientHello. We keep it using
571                  * |num_recs| for the sake of consistency
572                  */
573                 thisrr->type = SSL3_RT_HANDSHAKE;
574                 thisrr->rec_version = SSL2_VERSION;
575
576                 thisrr->length = sslv2len & 0x7fff;
577
578                 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
579                                      - SSL2_RT_HEADER_LENGTH) {
580                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
581                                 SSL_R_PACKET_LENGTH_TOO_LONG);
582                     return OSSL_RECORD_RETURN_FATAL;
583                 }
584             } else {
585                 /* SSLv3+ style record */
586
587                 /* Pull apart the header into the SSL3_RECORD */
588                 if (!PACKET_get_1(&pkt, &type)
589                         || !PACKET_get_net_2(&pkt, &version)
590                         || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
591                     if (rl->msg_callback != NULL)
592                         rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
593                     RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
594                     return OSSL_RECORD_RETURN_FATAL;
595                 }
596                 thisrr->type = type;
597                 thisrr->rec_version = version;
598
599                 /*
600                  * When we call validate_record_header() only records actually
601                  * received in SSLv2 format should have the record version set
602                  * to SSL2_VERSION. This way validate_record_header() can know
603                  * what format the record was in based on the version.
604                  */
605                 if (thisrr->rec_version == SSL2_VERSION) {
606                     RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
607                                 SSL_R_WRONG_VERSION_NUMBER);
608                     return OSSL_RECORD_RETURN_FATAL;
609                 }
610
611                 if (rl->msg_callback != NULL)
612                     rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
613
614                 if (thisrr->length >
615                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
616                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
617                                 SSL_R_PACKET_LENGTH_TOO_LONG);
618                     return OSSL_RECORD_RETURN_FATAL;
619                 }
620             }
621
622             if (!rl->funcs->validate_record_header(rl, thisrr)) {
623                 /* RLAYERfatal already called */
624                 return OSSL_RECORD_RETURN_FATAL;
625             }
626
627             /* now rl->rstate == SSL_ST_READ_BODY */
628         }
629
630         /*
631          * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
632          * how much more data we need to read for the rest of the record
633          */
634         if (thisrr->rec_version == SSL2_VERSION) {
635             more = thisrr->length + SSL2_RT_HEADER_LENGTH
636                    - SSL3_RT_HEADER_LENGTH;
637         } else {
638             more = thisrr->length;
639         }
640
641         if (more > 0) {
642             /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
643
644             rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
645             if (rret < OSSL_RECORD_RETURN_SUCCESS)
646                 return rret;     /* error or non-blocking io */
647         }
648
649         /* set state for later operations */
650         rl->rstate = SSL_ST_READ_HEADER;
651
652         /*
653          * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
654          * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
655          * + thisrr->length and we have that many bytes in rl->packet
656          */
657         if (thisrr->rec_version == SSL2_VERSION)
658             thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
659         else
660             thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
661
662         /*
663          * ok, we can now read from 'rl->packet' data into 'thisrr'.
664          * thisrr->input points at thisrr->length bytes, which need to be copied
665          * into thisrr->data by either the decryption or by the decompression.
666          * When the data is 'copied' into the thisrr->data buffer,
667          * thisrr->input will be updated to point at the new buffer
668          */
669
670         /*
671          * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
672          * thisrr->length bytes of encrypted compressed stuff.
673          */
674
675         /* decrypt in place in 'thisrr->input' */
676         thisrr->data = thisrr->input;
677         thisrr->orig_len = thisrr->length;
678
679         num_recs++;
680
681         /* we have pulled in a full packet so zero things */
682         rl->packet_length = 0;
683         rl->is_first_record = 0;
684     } while (num_recs < max_recs
685              && thisrr->type == SSL3_RT_APPLICATION_DATA
686              && RLAYER_USE_EXPLICIT_IV(rl)
687              && rl->enc_ctx != NULL
688              && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
689                  & EVP_CIPH_FLAG_PIPELINE) != 0
690              && tls_record_app_data_waiting(rl));
691
692     if (num_recs == 1
693             && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
694                /* The following can happen in tlsany_meth after HRR */
695             && rl->version == TLS1_3_VERSION
696             && rl->is_first_handshake) {
697         /*
698          * CCS messages must be exactly 1 byte long, containing the value 0x01
699          */
700         if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
701             RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
702                         SSL_R_INVALID_CCS_MESSAGE);
703             return OSSL_RECORD_RETURN_FATAL;
704         }
705         /*
706          * CCS messages are ignored in TLSv1.3. We treat it like an empty
707          * handshake record
708          */
709         thisrr->type = SSL3_RT_HANDSHAKE;
710         if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
711             RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
712                         SSL_R_UNEXPECTED_CCS_MESSAGE);
713             return OSSL_RECORD_RETURN_FATAL;
714         }
715         rl->num_recs = 0;
716         rl->curr_rec = 0;
717         rl->num_released = 0;
718
719         return OSSL_RECORD_RETURN_SUCCESS;
720     }
721
722     if (rl->md_ctx != NULL) {
723         const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
724
725         if (tmpmd != NULL) {
726             imac_size = EVP_MD_get_size(tmpmd);
727             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
728                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
729                 return OSSL_RECORD_RETURN_FATAL;
730             }
731             mac_size = (size_t)imac_size;
732         }
733     }
734
735     /*
736      * If in encrypt-then-mac mode calculate mac from encrypted record. All
737      * the details below are public so no timing details can leak.
738      */
739     if (rl->use_etm && rl->md_ctx) {
740         unsigned char *mac;
741
742         for (j = 0; j < num_recs; j++) {
743             thisrr = &rr[j];
744
745             if (thisrr->length < mac_size) {
746                 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
747                 return OSSL_RECORD_RETURN_FATAL;
748             }
749             thisrr->length -= mac_size;
750             mac = thisrr->data + thisrr->length;
751             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
752             if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
753                 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
754                             SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
755                 return OSSL_RECORD_RETURN_FATAL;
756             }
757         }
758         /*
759          * We've handled the mac now - there is no MAC inside the encrypted
760          * record
761          */
762         mac_size = 0;
763     }
764
765     if (mac_size > 0) {
766         macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
767         if (macbufs == NULL) {
768             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
769             return OSSL_RECORD_RETURN_FATAL;
770         }
771     }
772
773     enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
774
775     /*-
776      * enc_err is:
777      *    0: if the record is publicly invalid, or an internal error, or AEAD
778      *       decryption failed, or ETM decryption failed.
779      *    1: Success or MTE decryption failed (MAC will be randomised)
780      */
781     if (enc_err == 0) {
782         if (rl->alert != SSL_AD_NO_ALERT) {
783             /* RLAYERfatal() already got called */
784             goto end;
785         }
786         if (num_recs == 1
787                 && rl->skip_early_data != NULL
788                 && rl->skip_early_data(rl->cbarg)) {
789             /*
790              * Valid early_data that we cannot decrypt will fail here. We treat
791              * it like an empty record.
792              */
793
794             thisrr = &rr[0];
795
796             if (!rlayer_early_data_count_ok(rl, thisrr->length,
797                                             EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
798                 /* RLAYERfatal() already called */
799                 goto end;
800             }
801
802             thisrr->length = 0;
803             rl->num_recs = 0;
804             rl->curr_rec = 0;
805             rl->num_released = 0;
806             /* Reset the read sequence */
807             memset(rl->sequence, 0, sizeof(rl->sequence));
808             ret = 1;
809             goto end;
810         }
811         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
812                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
813         goto end;
814     }
815     OSSL_TRACE_BEGIN(TLS) {
816         BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
817         BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
818     } OSSL_TRACE_END(TLS);
819
820     /* r->length is now the compressed data plus mac */
821     if (rl->enc_ctx != NULL
822             && !rl->use_etm
823             && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
824         /* rl->md_ctx != NULL => mac_size != -1 */
825
826         for (j = 0; j < num_recs; j++) {
827             SSL_MAC_BUF *thismb = &macbufs[j];
828
829             thisrr = &rr[j];
830
831             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
832             if (i == 0 || thismb == NULL || thismb->mac == NULL
833                 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
834                 enc_err = 0;
835             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
836                 enc_err = 0;
837         }
838     }
839
840     if (enc_err == 0) {
841         if (rl->alert != SSL_AD_NO_ALERT) {
842             /* We already called RLAYERfatal() */
843             goto end;
844         }
845         /*
846          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
847          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
848          * failure is directly visible from the ciphertext anyway, we should
849          * not reveal which kind of error occurred -- this might become
850          * visible to an attacker (e.g. via a logfile)
851          */
852         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
853                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
854         goto end;
855     }
856
857     for (j = 0; j < num_recs; j++) {
858         thisrr = &rr[j];
859
860         if (!rl->funcs->post_process_record(rl, thisrr)) {
861             /* RLAYERfatal already called */
862             goto end;
863         }
864
865         /*
866          * Check if the received packet overflows the current
867          * Max Fragment Length setting.
868          * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
869          */
870         if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
871             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
872             goto end;
873         }
874
875         thisrr->off = 0;
876         /*-
877          * So at this point the following is true
878          * thisrr->type   is the type of record
879          * thisrr->length == number of bytes in record
880          * thisrr->off    == offset to first valid byte
881          * thisrr->data   == where to take bytes from, increment after use :-).
882          */
883
884         /* just read a 0 length packet */
885         if (thisrr->length == 0) {
886             if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
887                 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
888                             SSL_R_RECORD_TOO_SMALL);
889                 goto end;
890             }
891         } else {
892             rl->empty_record_count = 0;
893         }
894     }
895
896     if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
897         thisrr = &rr[0];
898         if (thisrr->type == SSL3_RT_APPLICATION_DATA
899                 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
900             /* RLAYERfatal already called */
901             goto end;
902         }
903     }
904
905     rl->num_recs = num_recs;
906     rl->curr_rec = 0;
907     rl->num_released = 0;
908     ret = OSSL_RECORD_RETURN_SUCCESS;
909  end:
910     if (macbufs != NULL) {
911         for (j = 0; j < num_recs; j++) {
912             if (macbufs[j].alloced)
913                 OPENSSL_free(macbufs[j].mac);
914         }
915         OPENSSL_free(macbufs);
916     }
917     return ret;
918 }
919
920 /* Shared by ssl3_meth and tls1_meth */
921 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
922 {
923     size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
924
925     if (rec->rec_version != rl->version) {
926         RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
927         return 0;
928     }
929
930 #ifndef OPENSSL_NO_COMP
931     /*
932      * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
933      * does not include the compression overhead anyway.
934      */
935     if (rl->expand == NULL)
936         len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
937 #endif
938
939     if (rec->length > len) {
940         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
941                     SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
942         return 0;
943     }
944
945     return 1;
946 }
947
948 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
949 {
950 #ifndef OPENSSL_NO_COMP
951     int i;
952
953     if (rec->comp == NULL) {
954         rec->comp = (unsigned char *)
955             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
956     }
957     if (rec->comp == NULL)
958         return 0;
959
960     i = COMP_expand_block(rl->expand, rec->comp, SSL3_RT_MAX_PLAIN_LENGTH,
961                           rec->data, (int)rec->length);
962     if (i < 0)
963         return 0;
964     else
965         rec->length = i;
966     rec->data = rec->comp;
967     return 1;
968 #else
969     return 0;
970 #endif
971 }
972
973 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
974 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
975 {
976     if (rl->expand != NULL) {
977         if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
978             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
979                         SSL_R_COMPRESSED_LENGTH_TOO_LONG);
980             return 0;
981         }
982         if (!tls_do_uncompress(rl, rec)) {
983             RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
984                         SSL_R_BAD_DECOMPRESSION);
985             return 0;
986         }
987     }
988
989     if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
990         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
991         return 0;
992     }
993
994     return 1;
995 }
996
997 /* Shared by tls13_meth and ktls_meth */
998 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
999 {
1000     if (rec->type != SSL3_RT_APPLICATION_DATA
1001             && rec->type != SSL3_RT_ALERT
1002             && rec->type != SSL3_RT_HANDSHAKE) {
1003         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
1004         return 0;
1005     }
1006
1007     if (rl->msg_callback != NULL)
1008         rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
1009                         1, rl->cbarg);
1010
1011     /*
1012      * TLSv1.3 alert and handshake records are required to be non-zero in
1013      * length.
1014      */
1015     if ((rec->type == SSL3_RT_HANDSHAKE || rec->type == SSL3_RT_ALERT)
1016             && rec->length == 0) {
1017         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
1018         return 0;
1019     }
1020
1021     return 1;
1022 }
1023
1024 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle, int *rversion,
1025                     int *type, unsigned char **data, size_t *datalen,
1026                     uint16_t *epoch, unsigned char *seq_num)
1027 {
1028     SSL3_RECORD *rec;
1029
1030     /*
1031      * tls_get_more_records() can return success without actually reading
1032      * anything useful (i.e. if empty records are read). We loop here until
1033      * we have something useful. tls_get_more_records() will eventually fail if
1034      * too many sequential empty records are read.
1035      */
1036     while (rl->curr_rec >= rl->num_recs) {
1037         int ret;
1038
1039         if (rl->num_released != rl->num_recs) {
1040             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
1041             return OSSL_RECORD_RETURN_FATAL;
1042         }
1043
1044         ret = rl->funcs->get_more_records(rl);
1045
1046         if (ret != OSSL_RECORD_RETURN_SUCCESS)
1047             return ret;
1048     }
1049
1050     /*
1051      * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
1052      * points to the next one to read.
1053      */
1054     rec = &rl->rrec[rl->curr_rec++];
1055
1056     *rechandle = rec;
1057     *rversion = rec->rec_version;
1058     *type = rec->type;
1059     *data = rec->data + rec->off;
1060     *datalen = rec->length;
1061     if (rl->isdtls) {
1062         *epoch = rec->epoch;
1063         memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
1064     }
1065
1066     return OSSL_RECORD_RETURN_SUCCESS;
1067 }
1068
1069 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
1070 {
1071     if (!ossl_assert(rl->num_released < rl->curr_rec)
1072             || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
1073         /* Should not happen */
1074         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1075         return OSSL_RECORD_RETURN_FATAL;
1076     }
1077
1078     rl->num_released++;
1079
1080     if (rl->curr_rec == rl->num_released
1081             && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
1082             && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
1083         tls_release_read_buffer(rl);
1084
1085     return OSSL_RECORD_RETURN_SUCCESS;
1086 }
1087
1088 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
1089 {
1090     const OSSL_PARAM *p;
1091
1092     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1093     if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1094         ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1095         return 0;
1096     }
1097
1098     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1099     if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1100         ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1101         return 0;
1102     }
1103
1104     if (rl->direction == OSSL_RECORD_DIRECTION_READ) {
1105         p = OSSL_PARAM_locate_const(options,
1106                                     OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1107         if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1108             ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1109             return 0;
1110         }
1111     } else {
1112         p = OSSL_PARAM_locate_const(options,
1113                                     OSSL_LIBSSL_RECORD_LAYER_PARAM_BLOCK_PADDING);
1114         if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->block_padding)) {
1115             ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1116             return 0;
1117         }
1118     }
1119
1120     if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1121         /*
1122          * We ignore any read_ahead setting prior to the application protection
1123          * level. Otherwise we may read ahead data in a lower protection level
1124          * that is destined for a higher protection level. To simplify the logic
1125          * we don't support that at this stage.
1126          */
1127         p = OSSL_PARAM_locate_const(options,
1128                                     OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1129         if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1130             ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1131             return 0;
1132         }
1133     }
1134
1135     return 1;
1136 }
1137
1138 int
1139 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1140                          int role, int direction, int level, unsigned char *key,
1141                          size_t keylen, unsigned char *iv, size_t ivlen,
1142                          unsigned char *mackey, size_t mackeylen,
1143                          const EVP_CIPHER *ciph, size_t taglen,
1144                          int mactype,
1145                          const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1146                          BIO *transport, BIO *next, BIO_ADDR *local,
1147                          BIO_ADDR *peer, const OSSL_PARAM *settings,
1148                          const OSSL_PARAM *options,
1149                          const OSSL_DISPATCH *fns, void *cbarg,
1150                          OSSL_RECORD_LAYER **retrl)
1151 {
1152     OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1153     const OSSL_PARAM *p;
1154
1155     *retrl = NULL;
1156
1157     if (rl == NULL) {
1158         ERR_raise(ERR_LIB_SSL, ERR_R_MALLOC_FAILURE);
1159         return OSSL_RECORD_RETURN_FATAL;
1160     }
1161
1162     /* Loop through all the settings since they must all be understood */
1163     if (settings != NULL) {
1164         for (p = settings; p->key != NULL; p++) {
1165             if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1166                 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1167                     ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1168                     goto err;
1169                 }
1170             } else if (strcmp(p->key,
1171                               OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1172                 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1173                     ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1174                     goto err;
1175                 }
1176             } else if (strcmp(p->key,
1177                               OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1178                 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1179                     ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1180                     goto err;
1181                 }
1182             } else if (strcmp(p->key,
1183                               OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1184                 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1185                     ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1186                     goto err;
1187                 }
1188             } else if (strcmp(p->key,
1189                               OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1190                 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1191                     ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1192                     goto err;
1193                 }
1194             } else {
1195                 ERR_raise(ERR_LIB_SSL, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1196                 goto err;
1197             }
1198         }
1199     }
1200
1201     rl->libctx = libctx;
1202     rl->propq = propq;
1203
1204     rl->version = vers;
1205     rl->role = role;
1206     rl->direction = direction;
1207     rl->level = level;
1208
1209     rl->alert = SSL_AD_NO_ALERT;
1210
1211     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1212         rl->is_first_record = 1;
1213
1214     if (!tls_set1_bio(rl, transport))
1215         goto err;
1216
1217     if (prev != NULL && !BIO_up_ref(prev))
1218         goto err;
1219     rl->prev = prev;
1220
1221     if (next != NULL && !BIO_up_ref(next))
1222         goto err;
1223     rl->next = next;
1224
1225     rl->cbarg = cbarg;
1226     if (fns != NULL) {
1227         for (; fns->function_id != 0; fns++) {
1228             switch (fns->function_id) {
1229             case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1230                 rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1231                 break;
1232             case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1233                 rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1234                 break;
1235             case OSSL_FUNC_RLAYER_SECURITY:
1236                 rl->security = OSSL_FUNC_rlayer_security(fns);
1237                 break;
1238             case OSSL_FUNC_RLAYER_PADDING:
1239                 rl->padding = OSSL_FUNC_rlayer_padding(fns);
1240             default:
1241                 /* Just ignore anything we don't understand */
1242                 break;
1243             }
1244         }
1245     }
1246
1247     if (!tls_set_options(rl, options)) {
1248         ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1249         goto err;
1250     }
1251
1252     if ((rl->options & SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS) == 0
1253             && rl->version <= TLS1_VERSION
1254             && !EVP_CIPHER_is_a(ciph, "NULL")
1255             && !EVP_CIPHER_is_a(ciph, "RC4")) {
1256         /*
1257          * Enable vulnerability countermeasure for CBC ciphers with known-IV
1258          * problem (http://www.openssl.org/~bodo/tls-cbc.txt)
1259          */
1260         rl->need_empty_fragments = 1;
1261     }
1262
1263     *retrl = rl;
1264     return OSSL_RECORD_RETURN_SUCCESS;
1265  err:
1266     tls_int_free(rl);
1267     return OSSL_RECORD_RETURN_FATAL;
1268 }
1269
1270 static int
1271 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1272                      int role, int direction, int level, uint16_t epoch,
1273                      unsigned char *key, size_t keylen, unsigned char *iv,
1274                      size_t ivlen, unsigned char *mackey, size_t mackeylen,
1275                      const EVP_CIPHER *ciph, size_t taglen,
1276                      int mactype,
1277                      const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1278                      BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1279                      const OSSL_PARAM *settings, const OSSL_PARAM *options,
1280                      const OSSL_DISPATCH *fns, void *cbarg,
1281                      OSSL_RECORD_LAYER **retrl)
1282 {
1283     int ret;
1284
1285     ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1286                                    key, keylen, iv, ivlen, mackey, mackeylen,
1287                                    ciph, taglen, mactype, md, comp, prev,
1288                                    transport, next, local, peer, settings,
1289                                    options, fns, cbarg, retrl);
1290
1291     if (ret != OSSL_RECORD_RETURN_SUCCESS)
1292         return ret;
1293
1294     switch (vers) {
1295     case TLS_ANY_VERSION:
1296         (*retrl)->funcs = &tls_any_funcs;
1297         break;
1298     case TLS1_3_VERSION:
1299         (*retrl)->funcs = &tls_1_3_funcs;
1300         break;
1301     case TLS1_2_VERSION:
1302     case TLS1_1_VERSION:
1303     case TLS1_VERSION:
1304         (*retrl)->funcs = &tls_1_funcs;
1305         break;
1306     case SSL3_VERSION:
1307         (*retrl)->funcs = &ssl_3_0_funcs;
1308         break;
1309     default:
1310         /* Should not happen */
1311         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1312         ret = OSSL_RECORD_RETURN_FATAL;
1313         goto err;
1314     }
1315
1316     ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1317                                             ivlen, mackey, mackeylen, ciph,
1318                                             taglen, mactype, md, comp);
1319
1320  err:
1321     if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1322         OPENSSL_free(*retrl);
1323         *retrl = NULL;
1324     }
1325     return ret;
1326 }
1327
1328 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1329 {
1330     BIO_free(rl->prev);
1331     BIO_free(rl->bio);
1332     BIO_free(rl->next);
1333     SSL3_BUFFER_release(&rl->rbuf);
1334
1335     tls_release_write_buffer(rl);
1336
1337     EVP_CIPHER_CTX_free(rl->enc_ctx);
1338     EVP_MD_CTX_free(rl->md_ctx);
1339 #ifndef OPENSSL_NO_COMP
1340     COMP_CTX_free(rl->expand);
1341 #endif
1342
1343     if (rl->version == SSL3_VERSION)
1344         OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1345
1346     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
1347
1348     OPENSSL_free(rl);
1349 }
1350
1351 int tls_free(OSSL_RECORD_LAYER *rl)
1352 {
1353     SSL3_BUFFER *rbuf;
1354     size_t left, written;
1355     int ret = 1;
1356
1357     rbuf = &rl->rbuf;
1358
1359     left = SSL3_BUFFER_get_left(rbuf);
1360     if (left > 0) {
1361         /*
1362          * This record layer is closing but we still have data left in our
1363          * buffer. It must be destined for the next epoch - so push it there.
1364          */
1365         ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1366     }
1367     tls_int_free(rl);
1368
1369     return ret;
1370 }
1371
1372 int tls_reset(OSSL_RECORD_LAYER *rl)
1373 {
1374     memset(rl, 0, sizeof(*rl));
1375     return 1;
1376 }
1377
1378 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1379 {
1380     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1381 }
1382
1383 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1384 {
1385     return rl->curr_rec < rl->num_recs;
1386 }
1387
1388 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1389 {
1390     size_t i;
1391     size_t num = 0;
1392
1393     for (i = rl->curr_rec; i < rl->num_recs; i++) {
1394         if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1395             return num;
1396         num += rl->rrec[i].length;
1397     }
1398     return num;
1399 }
1400
1401 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1402 {
1403     return 0;
1404 }
1405
1406 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1407 {
1408     return 0;
1409 }
1410
1411 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1412 {
1413     return 0;
1414 }
1415
1416 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1417                       size_t numtempl)
1418 {
1419     WPACKET pkt[SSL_MAX_PIPELINES + 1];
1420     SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1421     WPACKET *thispkt;
1422     SSL3_RECORD *thiswr;
1423     unsigned char *recordstart;
1424     int mac_size, clear = 0;
1425     int eivlen = 0;
1426     size_t align = 0;
1427     SSL3_BUFFER *wb;
1428     SSL_SESSION *sess;
1429     size_t totlen = 0, len, wpinited = 0;
1430     size_t j, prefix = 0;
1431     int using_ktls;
1432     /* TODO(RECLAYER): REMOVE ME */
1433     SSL_CONNECTION *s = rl->cbarg;
1434     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1435     OSSL_RECORD_TEMPLATE prefixtempl;
1436     OSSL_RECORD_TEMPLATE *thistempl;
1437
1438     /* Check we don't have pending data waiting to write */
1439     if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1440                      || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1441         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1442         goto err;
1443     }
1444
1445     sess = s->session;
1446
1447     if ((sess == NULL)
1448             || (s->enc_write_ctx == NULL)
1449             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
1450         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
1451         mac_size = 0;
1452     } else {
1453         mac_size = EVP_MD_CTX_get_size(s->write_hash);
1454         if (mac_size < 0) {
1455             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1456             goto err;
1457         }
1458     }
1459
1460     /*
1461      * 'create_empty_fragment' is true only when we have recursively called
1462      * ourselves.
1463      * Do we need to do that recursion in order to add an empty record prefix?
1464      */
1465     prefix = rl->need_empty_fragments
1466              && !clear
1467              && templates[0].type == SSL3_RT_APPLICATION_DATA;
1468
1469     if (rl->numwpipes < numtempl + prefix) {
1470         /*
1471          * TODO(RECLAYER): In the prefix case the first buffer can be a lot
1472          * smaller. It is wasteful to allocate a full sized buffer here
1473          */
1474         if (!tls_setup_write_buffer(rl, numtempl + prefix, 0)) {
1475             /* SSLfatal() already called */
1476             return -1;
1477         }
1478     }
1479
1480     using_ktls = BIO_get_ktls_send(rl->bio);
1481     if (!ossl_assert(!using_ktls || !prefix)) {
1482         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1483         goto err;
1484     }
1485
1486     if (prefix) {
1487         /*
1488          * countermeasure against known-IV weakness in CBC ciphersuites (see
1489          * http://www.openssl.org/~bodo/tls-cbc.txt)
1490          */
1491         prefixtempl.buf = NULL;
1492         prefixtempl.version = templates[0].version;
1493         prefixtempl.buflen = 0;
1494         prefixtempl.type = SSL3_RT_APPLICATION_DATA;
1495         wpinited = 1;
1496
1497         wb = &rl->wbuf[0];
1498         /* TODO(RECLAYER): This alignment calculation no longer seems right */
1499 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
1500         /*
1501          * extra fragment would be couple of cipher blocks, which would be
1502          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
1503          * payload, then we can just pretend we simply have two headers.
1504          */
1505         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
1506         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1507 #endif
1508         SSL3_BUFFER_set_offset(wb, align);
1509         if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
1510                                      SSL3_BUFFER_get_len(wb), 0)
1511                 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
1512             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1513             goto err;
1514         }
1515         wpinited = 1;
1516     }
1517     for (j = 0; j < numtempl; j++) {
1518         thispkt = &pkt[prefix + j];
1519
1520         wb = &rl->wbuf[prefix + j];
1521         wb->type = templates[j].type;
1522
1523         if (using_ktls) {
1524             /*
1525             * ktls doesn't modify the buffer, but to avoid a warning we need
1526             * to discard the const qualifier.
1527             * This doesn't leak memory because the buffers have been
1528             * released when switching to ktls.
1529             */
1530             SSL3_BUFFER_set_buf(wb, (unsigned char *)templates[j].buf);
1531             SSL3_BUFFER_set_offset(wb, 0);
1532             SSL3_BUFFER_set_app_buffer(wb, 1);
1533         } else {
1534 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1535             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
1536             align = SSL3_ALIGN_PAYLOAD - 1
1537                     - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1538 #endif
1539             /* TODO(RECLAYER): Is this alignment actually used somewhere? */
1540             SSL3_BUFFER_set_offset(wb, align);
1541             if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1542                                         SSL3_BUFFER_get_len(wb), 0)
1543                     || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
1544                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1545                 goto err;
1546             }
1547             wpinited++;
1548         }
1549     }
1550
1551     if (!using_ktls) {
1552         /* Explicit IV length, block ciphers appropriate version flag */
1553         if (s->enc_write_ctx != NULL && RLAYER_USE_EXPLICIT_IV(rl)
1554             && rl->version != TLS1_3_VERSION) {
1555             int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
1556             if (mode == EVP_CIPH_CBC_MODE) {
1557                 eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
1558                 if (eivlen < 0) {
1559                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
1560                     goto err;
1561                 }
1562                 if (eivlen <= 1)
1563                     eivlen = 0;
1564             } else if (mode == EVP_CIPH_GCM_MODE) {
1565                 /* Need explicit part of IV for GCM mode */
1566                 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1567             } else if (mode == EVP_CIPH_CCM_MODE) {
1568                 eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1569             }
1570         }
1571     }
1572
1573     totlen = 0;
1574     /* Clear our SSL3_RECORD structures */
1575     memset(wr, 0, sizeof(wr));
1576     for (j = 0; j < numtempl + prefix; j++) {
1577         unsigned char *compressdata = NULL;
1578         size_t maxcomplen;
1579         unsigned int rectype;
1580
1581         thispkt = &pkt[j];
1582         thiswr = &wr[j];
1583         thistempl = (j == 0 && prefix == 1) ? &prefixtempl :
1584                                               &templates[j - prefix];
1585
1586         /*
1587          * In TLSv1.3, once encrypting, we always use application data for the
1588          * record type
1589          */
1590         if (rl->version == TLS1_3_VERSION
1591                 && s->enc_write_ctx != NULL
1592                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1593                     || thistempl->type != SSL3_RT_ALERT))
1594             rectype = SSL3_RT_APPLICATION_DATA;
1595         else
1596             rectype = thistempl->type;
1597
1598         SSL3_RECORD_set_type(thiswr, rectype);
1599         SSL3_RECORD_set_rec_version(thiswr, thistempl->version);
1600
1601         maxcomplen = thistempl->buflen;
1602         if (s->compress != NULL)
1603             maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1604
1605         /*
1606          * When using offload kernel will write the header.
1607          * Otherwise write the header now
1608          */
1609         if (!using_ktls
1610                 && (!WPACKET_put_bytes_u8(thispkt, rectype)
1611                 || !WPACKET_put_bytes_u16(thispkt, thistempl->version)
1612                 || !WPACKET_start_sub_packet_u16(thispkt)
1613                 || (eivlen > 0
1614                     && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
1615                 || (maxcomplen > 0
1616                     && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1617                                               &compressdata)))) {
1618             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1619             goto err;
1620         }
1621
1622         /* lets setup the record stuff. */
1623         SSL3_RECORD_set_data(thiswr, compressdata);
1624         SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1625         /*
1626          * TODO(RECLAYER): Cast away the const. Should be safe - by why is this
1627          * necessary?
1628          */
1629         SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1630         totlen += thistempl->buflen;
1631
1632         /*
1633          * we now 'read' from thiswr->input, thiswr->length bytes into
1634          * thiswr->data
1635          */
1636
1637         /* first we compress */
1638         if (s->compress != NULL) {
1639             if (!ssl3_do_compress(s, thiswr)
1640                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1641                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1642                 goto err;
1643             }
1644         } else {
1645             if (using_ktls) {
1646                 SSL3_RECORD_reset_data(&wr[j]);
1647             } else {
1648                 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1649                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1650                     goto err;
1651                 }
1652                 SSL3_RECORD_reset_input(&wr[j]);
1653             }
1654         }
1655
1656         if (rl->version == TLS1_3_VERSION
1657                 && !using_ktls
1658                 && s->enc_write_ctx != NULL
1659                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
1660                     || thistempl->type != SSL3_RT_ALERT)) {
1661             size_t rlen, max_send_fragment;
1662
1663             if (!WPACKET_put_bytes_u8(thispkt, thistempl->type)) {
1664                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1665                 goto err;
1666             }
1667             SSL3_RECORD_add_length(thiswr, 1);
1668
1669             /* Add TLS1.3 padding */
1670             max_send_fragment = ssl_get_max_send_fragment(s);
1671             rlen = SSL3_RECORD_get_length(thiswr);
1672             if (rlen < max_send_fragment) {
1673                 size_t padding = 0;
1674                 size_t max_padding = max_send_fragment - rlen;
1675
1676                 if (rl->padding != NULL) {
1677                     padding = rl->padding(rl->cbarg, thistempl->type, rlen);
1678                 } else if (rl->block_padding > 0) {
1679                     size_t mask = rl->block_padding - 1;
1680                     size_t remainder;
1681
1682                     /* optimize for power of 2 */
1683                     if ((rl->block_padding & mask) == 0)
1684                         remainder = rlen & mask;
1685                     else
1686                         remainder = rlen % rl->block_padding;
1687                     /* don't want to add a block of padding if we don't have to */
1688                     if (remainder == 0)
1689                         padding = 0;
1690                     else
1691                         padding = rl->block_padding - remainder;
1692                 }
1693                 if (padding > 0) {
1694                     /* do not allow the record to exceed max plaintext length */
1695                     if (padding > max_padding)
1696                         padding = max_padding;
1697                     if (!WPACKET_memset(thispkt, 0, padding)) {
1698                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1699                                  ERR_R_INTERNAL_ERROR);
1700                         goto err;
1701                     }
1702                     SSL3_RECORD_add_length(thiswr, padding);
1703                 }
1704             }
1705         }
1706
1707         /*
1708          * we should still have the output to thiswr->data and the input from
1709          * wr->input. Length should be thiswr->length. thiswr->data still points
1710          * in the wb->buf
1711          */
1712
1713         if (!using_ktls && !rl->use_etm && mac_size != 0) {
1714             unsigned char *mac;
1715
1716             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1717                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1718                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1719                 goto err;
1720             }
1721         }
1722
1723         /*
1724          * Reserve some bytes for any growth that may occur during encryption.
1725          * This will be at most one cipher block or the tag length if using
1726          * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1727          */
1728         if (!using_ktls) {
1729             if (!WPACKET_reserve_bytes(thispkt,
1730                                         SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1731                                         NULL)
1732                 /*
1733                  * We also need next the amount of bytes written to this
1734                  * sub-packet
1735                  */
1736                 || !WPACKET_get_length(thispkt, &len)) {
1737             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1738             goto err;
1739             }
1740
1741             /* Get a pointer to the start of this record excluding header */
1742             recordstart = WPACKET_get_curr(thispkt) - len;
1743             SSL3_RECORD_set_data(thiswr, recordstart);
1744             SSL3_RECORD_reset_input(thiswr);
1745             SSL3_RECORD_set_length(thiswr, len);
1746         }
1747     }
1748
1749     if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1750         /*
1751          * We haven't actually negotiated the version yet, but we're trying to
1752          * send early data - so we need to use the tls13enc function.
1753          */
1754         if (tls13_enc(s, wr, numtempl, 1, NULL, mac_size) < 1) {
1755             if (!ossl_statem_in_error(s)) {
1756                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1757             }
1758             goto err;
1759         }
1760     } else {
1761         if (!using_ktls) {
1762             if (prefix) {
1763                 if (ssl->method->ssl3_enc->enc(s, wr, 1, 1, NULL, mac_size) < 1) {
1764                     if (!ossl_statem_in_error(s)) {
1765                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1766                     }
1767                     goto err;
1768                 }
1769             }
1770             if (ssl->method->ssl3_enc->enc(s, wr + prefix, numtempl, 1, NULL,
1771                                            mac_size) < 1) {
1772                 if (!ossl_statem_in_error(s)) {
1773                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1774                 }
1775                 goto err;
1776             }
1777         }
1778     }
1779
1780     for (j = 0; j < prefix + numtempl; j++) {
1781         size_t origlen;
1782
1783         thispkt = &pkt[j];
1784         thiswr = &wr[j];
1785         thistempl = (prefix == 1 && j == 0) ? &prefixtempl
1786                                             : &templates[j - prefix];
1787
1788         if (using_ktls)
1789             goto mac_done;
1790
1791         /* Allocate bytes for the encryption overhead */
1792         if (!WPACKET_get_length(thispkt, &origlen)
1793                    /* Encryption should never shrink the data! */
1794                 || origlen > thiswr->length
1795                 || (thiswr->length > origlen
1796                     && !WPACKET_allocate_bytes(thispkt,
1797                                                thiswr->length - origlen,
1798                                                NULL))) {
1799             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1800             goto err;
1801         }
1802         if (rl->use_etm && mac_size != 0) {
1803             unsigned char *mac;
1804
1805             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1806                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1807                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1808                 goto err;
1809             }
1810             SSL3_RECORD_add_length(thiswr, mac_size);
1811         }
1812
1813         if (!WPACKET_get_length(thispkt, &len)
1814                 || !WPACKET_close(thispkt)) {
1815             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1816             goto err;
1817         }
1818
1819         if (rl->msg_callback) {
1820             recordstart = WPACKET_get_curr(thispkt) - len
1821                           - SSL3_RT_HEADER_LENGTH;
1822             rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1823                              SSL3_RT_HEADER_LENGTH, rl->cbarg);
1824
1825             if (rl->version == TLS1_3_VERSION && s->enc_write_ctx != NULL) {
1826                 unsigned char ctype = thistempl->type;
1827
1828                 rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1829                                  &ctype, 1, rl->cbarg);
1830             }
1831         }
1832
1833         if (!WPACKET_finish(thispkt)) {
1834             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1835             goto err;
1836         }
1837
1838         /* header is added by the kernel when using offload */
1839         SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1840
1841  mac_done:
1842         /*
1843          * we should now have thiswr->data pointing to the encrypted data, which
1844          * is thiswr->length long.
1845          * Setting the type is not needed but helps for debugging
1846          */
1847         SSL3_RECORD_set_type(thiswr, thistempl->type);
1848
1849         /* now let's set up wb */
1850         SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1851     }
1852
1853     rl->nextwbuf = 0;
1854     /* we now just need to write the buffers */
1855     return tls_retry_write_records(rl);
1856  err:
1857     for (j = 0; j < wpinited; j++)
1858         WPACKET_cleanup(&pkt[j]);
1859     return -1;
1860 }
1861
1862 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1863  *
1864  * Return values are as per SSL_write()
1865  */
1866 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1867 {
1868     int i;
1869     SSL3_BUFFER *thiswb;
1870     size_t tmpwrit = 0;
1871     SSL_CONNECTION *s = rl->cbarg;
1872
1873     if (rl->nextwbuf >= rl->numwpipes)
1874         return 1;
1875
1876     for (;;) {
1877         thiswb = &rl->wbuf[rl->nextwbuf];
1878
1879         clear_sys_error();
1880         if (rl->bio != NULL) {
1881             s->rwstate = SSL_WRITING;
1882
1883             /*
1884              * To prevent coalescing of control and data messages,
1885              * such as in buffer_write, we flush the BIO
1886              */
1887             if (BIO_get_ktls_send(rl->bio)
1888                     && thiswb->type != SSL3_RT_APPLICATION_DATA) {
1889                 i = BIO_flush(rl->bio);
1890                 if (i <= 0)
1891                     return i;
1892                 BIO_set_ktls_ctrl_msg(rl->bio, thiswb->type);
1893             }
1894             i = BIO_write(rl->bio, (char *)
1895                           &(SSL3_BUFFER_get_buf(thiswb)
1896                             [SSL3_BUFFER_get_offset(thiswb)]),
1897                           (unsigned int)SSL3_BUFFER_get_left(thiswb));
1898             if (i >= 0)
1899                 tmpwrit = i;
1900         } else {
1901             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1902             i = -1;
1903         }
1904
1905         /*
1906          * When an empty fragment is sent on a connection using KTLS,
1907          * it is sent as a write of zero bytes.  If this zero byte
1908          * write succeeds, i will be 0 rather than a non-zero value.
1909          * Treat i == 0 as success rather than an error for zero byte
1910          * writes to permit this case.
1911          */
1912         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1913             SSL3_BUFFER_set_left(thiswb, 0);
1914             SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1915             if (++(rl->nextwbuf) < rl->numwpipes)
1916                 continue;
1917             s->rwstate = SSL_NOTHING;
1918
1919             if (rl->nextwbuf == rl->numwpipes
1920                     && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1921                 tls_release_write_buffer(rl);
1922             return 1;
1923         } else if (i <= 0) {
1924             if (rl->isdtls) {
1925                 /*
1926                  * For DTLS, just drop it. That's kind of the whole point in
1927                  * using a datagram service
1928                  */
1929                 SSL3_BUFFER_set_left(thiswb, 0);
1930                 if (++(rl->nextwbuf) == rl->numwpipes
1931                         && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1932                     tls_release_write_buffer(rl);
1933
1934             }
1935             return i;
1936         }
1937         SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1938         SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1939     }
1940 }
1941
1942 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1943 {
1944     return rl->alert;
1945 }
1946
1947 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1948 {
1949     if (bio != NULL && !BIO_up_ref(bio))
1950         return 0;
1951     BIO_free(rl->bio);
1952     rl->bio = bio;
1953
1954     return 1;
1955 }
1956
1957 /* Shared by most methods except tlsany_meth */
1958 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1959 {
1960     if (rl->version != version)
1961         return 0;
1962
1963     return 1;
1964 }
1965
1966 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1967 {
1968     return rl->funcs->set_protocol_version(rl, version);
1969 }
1970
1971 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1972 {
1973     rl->allow_plain_alerts = allow;
1974 }
1975
1976 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1977 {
1978     rl->is_first_handshake = first;
1979 }
1980
1981 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1982 {
1983     rl->max_pipelines = max_pipelines;
1984     if (max_pipelines > 1)
1985         rl->read_ahead = 1;
1986 }
1987
1988 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1989                    const char **longstr)
1990 {
1991     const char *shrt, *lng;
1992
1993     switch (rl->rstate) {
1994     case SSL_ST_READ_HEADER:
1995         shrt = "RH";
1996         lng = "read header";
1997         break;
1998     case SSL_ST_READ_BODY:
1999         shrt = "RB";
2000         lng = "read body";
2001         break;
2002     default:
2003         shrt = lng = "unknown";
2004         break;
2005     }
2006     if (shortstr != NULL)
2007         *shortstr = shrt;
2008     if (longstr != NULL)
2009         *longstr = lng;
2010 }
2011
2012 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2013     tls_new_record_layer,
2014     tls_free,
2015     tls_reset,
2016     tls_unprocessed_read_pending,
2017     tls_processed_read_pending,
2018     tls_app_data_pending,
2019     tls_write_pending,
2020     tls_get_max_record_len,
2021     tls_get_max_records,
2022     tls_write_records,
2023     tls_retry_write_records,
2024     tls_read_record,
2025     tls_release_record,
2026     tls_get_alert_code,
2027     tls_set1_bio,
2028     tls_set_protocol_version,
2029     tls_set_plain_alerts,
2030     tls_set_first_handshake,
2031     tls_set_max_pipelines,
2032     NULL,
2033     tls_get_state,
2034     tls_set_options
2035 };