a7b31163c541457ae5a6a74565e99d29e691d1f8
[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     if (rl == NULL)
1402         return 1;
1403
1404     rbuf = &rl->rbuf;
1405
1406     left = SSL3_BUFFER_get_left(rbuf);
1407     if (left > 0) {
1408         /*
1409          * This record layer is closing but we still have data left in our
1410          * buffer. It must be destined for the next epoch - so push it there.
1411          */
1412         ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1413     }
1414     tls_int_free(rl);
1415
1416     return ret;
1417 }
1418
1419 int tls_reset(OSSL_RECORD_LAYER *rl)
1420 {
1421     memset(rl, 0, sizeof(*rl));
1422     return 1;
1423 }
1424
1425 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1426 {
1427     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1428 }
1429
1430 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1431 {
1432     return rl->curr_rec < rl->num_recs;
1433 }
1434
1435 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1436 {
1437     size_t i;
1438     size_t num = 0;
1439
1440     for (i = rl->curr_rec; i < rl->num_recs; i++) {
1441         if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1442             return num;
1443         num += rl->rrec[i].length;
1444     }
1445     return num;
1446 }
1447
1448 size_t tls_get_max_records_default(OSSL_RECORD_LAYER *rl, int type, size_t len,
1449                                    size_t maxfrag, size_t *preffrag)
1450 {
1451     /*
1452      * If we have a pipeline capable cipher, and we have been configured to use
1453      * it, then return the preferred number of pipelines.
1454      */
1455     if (rl->max_pipelines > 0
1456             && rl->enc_ctx != NULL
1457             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
1458                 & EVP_CIPH_FLAG_PIPELINE) != 0
1459             && RLAYER_USE_EXPLICIT_IV(rl)) {
1460         size_t pipes;
1461
1462         if (len == 0)
1463             return 1;
1464         pipes = ((len - 1) / *preffrag) + 1;
1465
1466         return (pipes < rl->max_pipelines) ? pipes : rl->max_pipelines;
1467     }
1468
1469     return 1;
1470 }
1471
1472 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
1473                            size_t maxfrag, size_t *preffrag)
1474 {
1475     return rl->funcs->get_max_records(rl, type, len, maxfrag, preffrag);
1476 }
1477
1478 int tls_allocate_write_buffers_default(OSSL_RECORD_LAYER *rl,
1479                                          OSSL_RECORD_TEMPLATE *templates,
1480                                          size_t numtempl,
1481                                          size_t *prefix)
1482 {
1483     if (!tls_setup_write_buffer(rl, numtempl, 0, 0)) {
1484         /* RLAYERfatal() already called */
1485         return 0;
1486     }
1487
1488     return 1;
1489 }
1490
1491 int tls_initialise_write_packets_default(OSSL_RECORD_LAYER *rl,
1492                                          OSSL_RECORD_TEMPLATE *templates,
1493                                          size_t numtempl,
1494                                          OSSL_RECORD_TEMPLATE *prefixtempl,
1495                                          WPACKET *pkt,
1496                                          SSL3_BUFFER *bufs,
1497                                          size_t *wpinited)
1498 {
1499     WPACKET *thispkt;
1500     size_t j, align;
1501     SSL3_BUFFER *wb;
1502
1503     for (j = 0; j < numtempl; j++) {
1504         thispkt = &pkt[j];
1505         wb = &bufs[j];
1506
1507         wb->type = templates[j].type;
1508
1509 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
1510         align = (size_t)SSL3_BUFFER_get_buf(wb);
1511         align += rl->isdtls ? DTLS1_RT_HEADER_LENGTH : SSL3_RT_HEADER_LENGTH;
1512         align = SSL3_ALIGN_PAYLOAD - 1
1513                 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
1514 #endif
1515         SSL3_BUFFER_set_offset(wb, align);
1516
1517         if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
1518                                      SSL3_BUFFER_get_len(wb), 0)) {
1519             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1520             return 0;
1521         }
1522         (*wpinited)++;
1523         if (!WPACKET_allocate_bytes(thispkt, align, NULL)) {
1524             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1525             return 0;
1526         }
1527     }
1528
1529     return 1;
1530 }
1531
1532 int tls_prepare_record_header_default(OSSL_RECORD_LAYER *rl,
1533                                       WPACKET *thispkt,
1534                                       OSSL_RECORD_TEMPLATE *templ,
1535                                       unsigned int rectype,
1536                                       unsigned char **recdata)
1537 {
1538     size_t maxcomplen;
1539
1540     *recdata = NULL;
1541
1542     maxcomplen = templ->buflen;
1543     if (rl->compctx != NULL)
1544         maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
1545
1546     if (!WPACKET_put_bytes_u8(thispkt, rectype)
1547             || !WPACKET_put_bytes_u16(thispkt, templ->version)
1548             || !WPACKET_start_sub_packet_u16(thispkt)
1549             || (rl->eivlen > 0
1550                 && !WPACKET_allocate_bytes(thispkt, rl->eivlen, NULL))
1551             || (maxcomplen > 0
1552                 && !WPACKET_reserve_bytes(thispkt, maxcomplen,
1553                                           recdata))) {
1554         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1555         return 0;
1556     }
1557
1558     return 1;
1559 }
1560
1561 int tls_prepare_for_encryption_default(OSSL_RECORD_LAYER *rl,
1562                                        size_t mac_size,
1563                                        WPACKET *thispkt,
1564                                        SSL3_RECORD *thiswr)
1565 {
1566     size_t len;
1567     unsigned char *recordstart;
1568
1569     /*
1570      * we should still have the output to thiswr->data and the input from
1571      * wr->input. Length should be thiswr->length. thiswr->data still points
1572      * in the wb->buf
1573      */
1574
1575     if (!rl->use_etm && mac_size != 0) {
1576         unsigned char *mac;
1577
1578         if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1579                 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1580             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1581             return 0;
1582         }
1583     }
1584
1585     /*
1586      * Reserve some bytes for any growth that may occur during encryption.
1587      * This will be at most one cipher block or the tag length if using
1588      * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1589      */
1590     if (!WPACKET_reserve_bytes(thispkt,
1591                                SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1592                                NULL)
1593             /*
1594              * We also need next the amount of bytes written to this
1595              * sub-packet
1596              */
1597             || !WPACKET_get_length(thispkt, &len)) {
1598         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1599         return 0;
1600     }
1601
1602     /* Get a pointer to the start of this record excluding header */
1603     recordstart = WPACKET_get_curr(thispkt) - len;
1604     SSL3_RECORD_set_data(thiswr, recordstart);
1605     SSL3_RECORD_reset_input(thiswr);
1606     SSL3_RECORD_set_length(thiswr, len);
1607
1608     return 1;
1609 }
1610
1611 int tls_post_encryption_processing_default(OSSL_RECORD_LAYER *rl,
1612                                            size_t mac_size,
1613                                            OSSL_RECORD_TEMPLATE *thistempl,
1614                                            WPACKET *thispkt,
1615                                            SSL3_RECORD *thiswr)
1616 {
1617     size_t origlen, len;
1618     size_t headerlen = rl->isdtls ? DTLS1_RT_HEADER_LENGTH
1619                                   : SSL3_RT_HEADER_LENGTH;
1620
1621     /* Allocate bytes for the encryption overhead */
1622     if (!WPACKET_get_length(thispkt, &origlen)
1623             /* Encryption should never shrink the data! */
1624             || origlen > thiswr->length
1625             || (thiswr->length > origlen
1626                 && !WPACKET_allocate_bytes(thispkt,
1627                                            thiswr->length - origlen,
1628                                            NULL))) {
1629         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1630         return 0;
1631     }
1632     if (rl->use_etm && mac_size != 0) {
1633         unsigned char *mac;
1634
1635         if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1636                 || !rl->funcs->mac(rl, thiswr, mac, 1)) {
1637             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1638             return 0;
1639         }
1640
1641         SSL3_RECORD_add_length(thiswr, mac_size);
1642     }
1643
1644     if (!WPACKET_get_length(thispkt, &len)
1645             || !WPACKET_close(thispkt)) {
1646         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1647         return 0;
1648     }
1649
1650     if (rl->msg_callback != NULL) {
1651         unsigned char *recordstart;
1652
1653         recordstart = WPACKET_get_curr(thispkt) - len - headerlen;
1654         rl->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1655                          headerlen, rl->cbarg);
1656
1657         if (rl->version == TLS1_3_VERSION && rl->enc_ctx != NULL) {
1658             unsigned char ctype = thistempl->type;
1659
1660             rl->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1661                              &ctype, 1, rl->cbarg);
1662         }
1663     }
1664
1665     if (!WPACKET_finish(thispkt)) {
1666         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1667         return 0;
1668     }
1669
1670     SSL3_RECORD_add_length(thiswr, headerlen);
1671
1672     return 1;
1673 }
1674
1675 int tls_write_records_default(OSSL_RECORD_LAYER *rl,
1676                               OSSL_RECORD_TEMPLATE *templates,
1677                               size_t numtempl)
1678 {
1679     WPACKET pkt[SSL_MAX_PIPELINES + 1];
1680     SSL3_RECORD wr[SSL_MAX_PIPELINES + 1];
1681     WPACKET *thispkt;
1682     SSL3_RECORD *thiswr;
1683     int mac_size = 0, ret = 0;
1684     size_t wpinited = 0;
1685     size_t j, prefix = 0;
1686     OSSL_RECORD_TEMPLATE prefixtempl;
1687     OSSL_RECORD_TEMPLATE *thistempl;
1688
1689     if (rl->md_ctx != NULL && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
1690         mac_size = EVP_MD_CTX_get_size(rl->md_ctx);
1691         if (mac_size < 0) {
1692             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1693             goto err;
1694         }
1695     }
1696
1697     if (!rl->funcs->allocate_write_buffers(rl, templates, numtempl, &prefix)) {
1698         /* RLAYERfatal() already called */
1699         goto err;
1700     }
1701
1702     if (!rl->funcs->initialise_write_packets(rl, templates, numtempl,
1703                                              &prefixtempl, pkt, rl->wbuf,
1704                                              &wpinited)) {
1705         /* RLAYERfatal() already called */
1706         goto err;
1707     }
1708
1709     /* Clear our SSL3_RECORD structures */
1710     memset(wr, 0, sizeof(wr));
1711     for (j = 0; j < numtempl + prefix; j++) {
1712         unsigned char *compressdata = NULL;
1713         unsigned int rectype;
1714
1715         thispkt = &pkt[j];
1716         thiswr = &wr[j];
1717         thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1718
1719         /*
1720          * Default to the record type as specified in the template unless the
1721          * protocol implementation says differently.
1722          */
1723         if (rl->funcs->get_record_type != NULL)
1724             rectype = rl->funcs->get_record_type(rl, thistempl);
1725         else
1726             rectype = thistempl->type;
1727
1728         SSL3_RECORD_set_type(thiswr, rectype);
1729         SSL3_RECORD_set_rec_version(thiswr, thistempl->version);
1730
1731         if (!rl->funcs->prepare_record_header(rl, thispkt, thistempl, rectype,
1732                                               &compressdata)) {
1733             /* RLAYERfatal() already called */
1734             goto err;
1735         }
1736
1737         /* lets setup the record stuff. */
1738         SSL3_RECORD_set_data(thiswr, compressdata);
1739         SSL3_RECORD_set_length(thiswr, thistempl->buflen);
1740
1741         SSL3_RECORD_set_input(thiswr, (unsigned char *)thistempl->buf);
1742
1743         /*
1744          * we now 'read' from thiswr->input, thiswr->length bytes into
1745          * thiswr->data
1746          */
1747
1748         /* first we compress */
1749         if (rl->compctx != NULL) {
1750             if (!tls_do_compress(rl, thiswr)
1751                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
1752                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
1753                 goto err;
1754             }
1755         } else if (compressdata != NULL) {
1756             if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
1757                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1758                 goto err;
1759             }
1760             SSL3_RECORD_reset_input(&wr[j]);
1761         }
1762
1763         if (rl->funcs->add_record_padding != NULL
1764                 && !rl->funcs->add_record_padding(rl, thistempl, thispkt,
1765                                                   thiswr)) {
1766             /* RLAYERfatal() already called */
1767             goto err;
1768         }
1769
1770         if (!rl->funcs->prepare_for_encryption(rl, mac_size, thispkt, thiswr)) {
1771             /* RLAYERfatal() already called */
1772             goto err;
1773         }
1774     }
1775
1776     if (prefix) {
1777         if (rl->funcs->cipher(rl, wr, 1, 1, NULL, mac_size) < 1) {
1778             if (rl->alert == SSL_AD_NO_ALERT) {
1779                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1780             }
1781             goto err;
1782         }
1783     }
1784
1785     if (rl->funcs->cipher(rl, wr + prefix, numtempl, 1, NULL, mac_size) < 1) {
1786         if (rl->alert == SSL_AD_NO_ALERT) {
1787             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1788         }
1789         goto err;
1790     }
1791
1792     for (j = 0; j < numtempl + prefix; j++) {
1793         thispkt = &pkt[j];
1794         thiswr = &wr[j];
1795         thistempl = (j < prefix) ? &prefixtempl : &templates[j - prefix];
1796
1797         if (!rl->funcs->post_encryption_processing(rl, mac_size, thistempl,
1798                                                    thispkt, thiswr)) {
1799             /* RLAYERfatal() already called */
1800             goto err;
1801         }
1802
1803         /* now let's set up wb */
1804         SSL3_BUFFER_set_left(&rl->wbuf[j], SSL3_RECORD_get_length(thiswr));
1805     }
1806
1807     ret = 1;
1808  err:
1809     for (j = 0; j < wpinited; j++)
1810         WPACKET_cleanup(&pkt[j]);
1811     return ret;
1812 }
1813
1814 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE *templates,
1815                       size_t numtempl)
1816 {
1817     /* Check we don't have pending data waiting to write */
1818     if (!ossl_assert(rl->nextwbuf >= rl->numwpipes
1819                      || SSL3_BUFFER_get_left(&rl->wbuf[rl->nextwbuf]) == 0)) {
1820         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1821         return OSSL_RECORD_RETURN_FATAL;
1822     }
1823
1824     if (!rl->funcs->write_records(rl, templates, numtempl)) {
1825         /* RLAYERfatal already called */
1826         return OSSL_RECORD_RETURN_FATAL;
1827     }
1828
1829     rl->nextwbuf = 0;
1830     /* we now just need to write the buffers */
1831     return tls_retry_write_records(rl);
1832 }
1833
1834 int tls_retry_write_records(OSSL_RECORD_LAYER *rl)
1835 {
1836     int i, ret;
1837     SSL3_BUFFER *thiswb;
1838     size_t tmpwrit = 0;
1839
1840     if (rl->nextwbuf >= rl->numwpipes)
1841         return OSSL_RECORD_RETURN_SUCCESS;
1842
1843     for (;;) {
1844         thiswb = &rl->wbuf[rl->nextwbuf];
1845
1846         clear_sys_error();
1847         if (rl->bio != NULL) {
1848             if (rl->funcs->prepare_write_bio != NULL) {
1849                 ret = rl->funcs->prepare_write_bio(rl, thiswb->type);
1850                 if (ret != OSSL_RECORD_RETURN_SUCCESS)
1851                     return ret;
1852             }
1853             i = BIO_write(rl->bio, (char *)
1854                           &(SSL3_BUFFER_get_buf(thiswb)
1855                             [SSL3_BUFFER_get_offset(thiswb)]),
1856                           (unsigned int)SSL3_BUFFER_get_left(thiswb));
1857             if (i >= 0) {
1858                 tmpwrit = i;
1859                 if (i == 0 && BIO_should_retry(rl->bio))
1860                     ret = OSSL_RECORD_RETURN_RETRY;
1861                 else
1862                     ret = OSSL_RECORD_RETURN_SUCCESS;
1863             } else {
1864                 if (BIO_should_retry(rl->bio))
1865                     ret = OSSL_RECORD_RETURN_RETRY;
1866                 else
1867                     ret = OSSL_RECORD_RETURN_FATAL;
1868             }
1869         } else {
1870             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1871             ret = OSSL_RECORD_RETURN_FATAL;
1872             i = -1;
1873         }
1874
1875         /*
1876          * When an empty fragment is sent on a connection using KTLS,
1877          * it is sent as a write of zero bytes.  If this zero byte
1878          * write succeeds, i will be 0 rather than a non-zero value.
1879          * Treat i == 0 as success rather than an error for zero byte
1880          * writes to permit this case.
1881          */
1882         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(thiswb)) {
1883             SSL3_BUFFER_set_left(thiswb, 0);
1884             SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1885             if (++(rl->nextwbuf) < rl->numwpipes)
1886                 continue;
1887
1888             if (rl->nextwbuf == rl->numwpipes
1889                     && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1890                 tls_release_write_buffer(rl);
1891             return OSSL_RECORD_RETURN_SUCCESS;
1892         } else if (i <= 0) {
1893             if (rl->isdtls) {
1894                 /*
1895                  * For DTLS, just drop it. That's kind of the whole point in
1896                  * using a datagram service
1897                  */
1898                 SSL3_BUFFER_set_left(thiswb, 0);
1899                 if (++(rl->nextwbuf) == rl->numwpipes
1900                         && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0)
1901                     tls_release_write_buffer(rl);
1902
1903             }
1904             return ret;
1905         }
1906         SSL3_BUFFER_add_offset(thiswb, tmpwrit);
1907         SSL3_BUFFER_sub_left(thiswb, tmpwrit);
1908     }
1909 }
1910
1911 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1912 {
1913     return rl->alert;
1914 }
1915
1916 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1917 {
1918     if (bio != NULL && !BIO_up_ref(bio))
1919         return 0;
1920     BIO_free(rl->bio);
1921     rl->bio = bio;
1922
1923     return 1;
1924 }
1925
1926 /* Shared by most methods except tlsany_meth */
1927 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1928 {
1929     if (rl->version != version)
1930         return 0;
1931
1932     return 1;
1933 }
1934
1935 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1936 {
1937     return rl->funcs->set_protocol_version(rl, version);
1938 }
1939
1940 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1941 {
1942     rl->allow_plain_alerts = allow;
1943 }
1944
1945 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1946 {
1947     rl->is_first_handshake = first;
1948 }
1949
1950 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1951 {
1952     rl->max_pipelines = max_pipelines;
1953     if (max_pipelines > 1)
1954         rl->read_ahead = 1;
1955 }
1956
1957 void tls_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
1958                    const char **longstr)
1959 {
1960     const char *shrt, *lng;
1961
1962     switch (rl->rstate) {
1963     case SSL_ST_READ_HEADER:
1964         shrt = "RH";
1965         lng = "read header";
1966         break;
1967     case SSL_ST_READ_BODY:
1968         shrt = "RB";
1969         lng = "read body";
1970         break;
1971     default:
1972         shrt = lng = "unknown";
1973         break;
1974     }
1975     if (shortstr != NULL)
1976         *shortstr = shrt;
1977     if (longstr != NULL)
1978         *longstr = lng;
1979 }
1980
1981 const COMP_METHOD *tls_get_compression(OSSL_RECORD_LAYER *rl)
1982 {
1983 #ifndef OPENSSL_NO_COMP
1984     return (rl->compctx == NULL) ? NULL : COMP_CTX_get_method(rl->compctx);
1985 #else
1986     return NULL;
1987 #endif
1988 }
1989
1990 void tls_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
1991 {
1992     rl->max_frag_len = max_frag_len;
1993     /*
1994      * We don't need to adjust buffer sizes. Write buffer sizes are
1995      * automatically checked anyway. We should only be changing the read buffer
1996      * size during the handshake, so we will create a new buffer when we create
1997      * the new record layer. We can't change the existing buffer because it may
1998      * already have data in it.
1999      */
2000 }
2001
2002 int tls_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
2003 {
2004     int i;
2005
2006     /* Increment the sequence counter */
2007     for (i = SEQ_NUM_SIZE; i > 0; i--) {
2008         ++(rl->sequence[i - 1]);
2009         if (rl->sequence[i - 1] != 0)
2010             break;
2011     }
2012     if (i == 0) {
2013         /* Sequence has wrapped */
2014         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_SEQUENCE_CTR_WRAPPED);
2015         return 0;
2016     }
2017     return 1;
2018 }
2019
2020 int tls_alloc_buffers(OSSL_RECORD_LAYER *rl)
2021 {
2022     if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2023         /* If we have a pending write then buffers are already allocated */
2024         if (rl->nextwbuf < rl->numwpipes)
2025             return 1;
2026         /*
2027          * We assume 1 pipe with default sized buffer. If what we need ends up
2028          * being a different size to that then it will be reallocated on demand.
2029          * If we need more than 1 pipe then that will also be allocated on
2030          * demand
2031          */
2032         if (!tls_setup_write_buffer(rl, 1, 0, 0))
2033             return 0;
2034
2035         /*
2036          * Normally when we allocate write buffers we immediately write
2037          * something into it. In this case we're not doing that so mark the
2038          * buffer as empty.
2039          */
2040         SSL3_BUFFER_set_left(&rl->wbuf[0], 0);
2041         return 1;
2042     }
2043
2044     /* Read direction */
2045
2046     /* If we have pending data to be read then buffers are already allocated */
2047     if (rl->curr_rec < rl->num_recs || SSL3_BUFFER_get_left(&rl->rbuf) != 0)
2048         return 1;
2049     return tls_setup_read_buffer(rl);
2050 }
2051
2052 int tls_free_buffers(OSSL_RECORD_LAYER *rl)
2053 {
2054     if (rl->direction == OSSL_RECORD_DIRECTION_WRITE) {
2055         if (rl->nextwbuf < rl->numwpipes) {
2056             /*
2057              * We may have pending data. If we've just got one empty buffer
2058              * allocated then it has probably just been alloc'd via
2059              * tls_alloc_buffers, and it is fine to free it. Otherwise this
2060              * looks like real pending data and it is an error.
2061              */
2062             if (rl->nextwbuf != 0
2063                     || rl->numwpipes != 1
2064                     || SSL3_BUFFER_get_left(&rl->wbuf[0]) != 0)
2065                 return 0;
2066         }
2067         tls_release_write_buffer(rl);
2068         return 1;
2069     }
2070
2071     /* Read direction */
2072
2073     /* If we have pending data to be read then fail */
2074     if (rl->curr_rec < rl->num_recs || SSL3_BUFFER_get_left(&rl->rbuf) != 0)
2075         return 0;
2076
2077     return tls_release_read_buffer(rl);
2078 }
2079
2080 const OSSL_RECORD_METHOD ossl_tls_record_method = {
2081     tls_new_record_layer,
2082     tls_free,
2083     tls_reset,
2084     tls_unprocessed_read_pending,
2085     tls_processed_read_pending,
2086     tls_app_data_pending,
2087     tls_get_max_records,
2088     tls_write_records,
2089     tls_retry_write_records,
2090     tls_read_record,
2091     tls_release_record,
2092     tls_get_alert_code,
2093     tls_set1_bio,
2094     tls_set_protocol_version,
2095     tls_set_plain_alerts,
2096     tls_set_first_handshake,
2097     tls_set_max_pipelines,
2098     NULL,
2099     tls_get_state,
2100     tls_set_options,
2101     tls_get_compression,
2102     tls_set_max_frag_len,
2103     NULL,
2104     tls_increment_sequence_ctr,
2105     tls_alloc_buffers,
2106     tls_free_buffers
2107 };