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