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