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