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