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