Remove some references to rlayer.rstate
[openssl.git] / ssl / record / methods / tls_common.c
1 /*
2  * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/bio.h>
11 #include <openssl/ssl.h>
12 #include <openssl/err.h>
13 #include <openssl/core_names.h>
14 #include "internal/e_os.h"
15 #include "internal/packet.h"
16 #include "../../ssl_local.h"
17 #include "../record_local.h"
18 #include "recmethod_local.h"
19
20 # define SSL_AD_NO_ALERT    -1
21
22 static void tls_int_free(OSSL_RECORD_LAYER *rl);
23
24 void ossl_rlayer_fatal(OSSL_RECORD_LAYER *rl, int al, int reason,
25                        const char *fmt, ...)
26 {
27     va_list args;
28
29     va_start(args, fmt);
30     ERR_vset_error(ERR_LIB_SSL, reason, fmt, args);
31     va_end(args);
32
33     rl->alert = al;
34 }
35
36 int ossl_set_tls_provider_parameters(OSSL_RECORD_LAYER *rl,
37                                      EVP_CIPHER_CTX *ctx,
38                                      const EVP_CIPHER *ciph,
39                                      const EVP_MD *md)
40 {
41     /*
42      * Provided cipher, the TLS padding/MAC removal is performed provider
43      * side so we need to tell the ctx about our TLS version and mac size
44      */
45     OSSL_PARAM params[3], *pprm = params;
46     size_t macsize = 0;
47     int imacsize = -1;
48
49     if ((EVP_CIPHER_get_flags(ciph) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0
50             && !rl->use_etm)
51         imacsize = EVP_MD_get_size(md);
52     if (imacsize >= 0)
53         macsize = (size_t)imacsize;
54
55     *pprm++ = OSSL_PARAM_construct_int(OSSL_CIPHER_PARAM_TLS_VERSION,
56                                        &rl->version);
57     *pprm++ = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_TLS_MAC_SIZE,
58                                           &macsize);
59     *pprm = OSSL_PARAM_construct_end();
60
61     if (!EVP_CIPHER_CTX_set_params(ctx, params)) {
62         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
63         return 0;
64     }
65
66     return 1;
67 }
68
69 /*
70  * ssl3_cbc_record_digest_supported returns 1 iff |ctx| uses a hash function
71  * which ssl3_cbc_digest_record supports.
72  */
73 char ssl3_cbc_record_digest_supported(const EVP_MD_CTX *ctx)
74 {
75     switch (EVP_MD_CTX_get_type(ctx)) {
76     case NID_md5:
77     case NID_sha1:
78     case NID_sha224:
79     case NID_sha256:
80     case NID_sha384:
81     case NID_sha512:
82         return 1;
83     default:
84         return 0;
85     }
86 }
87
88 #ifndef OPENSSL_NO_COMP
89 static int rlayer_allow_compression(OSSL_RECORD_LAYER *rl)
90 {
91     if (rl->options & SSL_OP_NO_COMPRESSION)
92         return 0;
93
94     return rl->security(rl->cbarg, SSL_SECOP_COMPRESSION, 0, 0, NULL);
95 }
96 #endif
97
98 int rlayer_setup_read_buffer(OSSL_RECORD_LAYER *rl)
99 {
100     unsigned char *p;
101     size_t len, align = 0, headerlen;
102     SSL3_BUFFER *b;
103
104     b = &rl->rbuf;
105
106     if (rl->isdtls)
107         headerlen = DTLS1_RT_HEADER_LENGTH;
108     else
109         headerlen = SSL3_RT_HEADER_LENGTH;
110
111 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
112     align = (-SSL3_RT_HEADER_LENGTH) & (SSL3_ALIGN_PAYLOAD - 1);
113 #endif
114
115     if (b->buf == NULL) {
116         len = SSL3_RT_MAX_PLAIN_LENGTH
117             + SSL3_RT_MAX_ENCRYPTED_OVERHEAD + headerlen + align;
118 #ifndef OPENSSL_NO_COMP
119         if (rlayer_allow_compression(rl))
120             len += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
121 #endif
122         if (b->default_len > len)
123             len = b->default_len;
124         if ((p = OPENSSL_malloc(len)) == NULL) {
125             /*
126              * We've got a malloc failure, and we're still initialising buffers.
127              * We assume we're so doomed that we won't even be able to send an
128              * alert.
129              */
130             RLAYERfatal(rl, SSL_AD_NO_ALERT, ERR_R_MALLOC_FAILURE);
131             return 0;
132         }
133         b->buf = p;
134         b->len = len;
135     }
136
137     return 1;
138 }
139
140 static int rlayer_release_read_buffer(OSSL_RECORD_LAYER *rl)
141 {
142     SSL3_BUFFER *b;
143
144     b = &rl->rbuf;
145     if (rl->options & SSL_OP_CLEANSE_PLAINTEXT)
146         OPENSSL_cleanse(b->buf, b->len);
147     OPENSSL_free(b->buf);
148     b->buf = NULL;
149     return 1;
150 }
151
152 /*
153  * Return values are as per SSL_read()
154  */
155 int tls_default_read_n(OSSL_RECORD_LAYER *rl, size_t n, size_t max, int extend,
156                        int clearold, size_t *readbytes)
157 {
158     /*
159      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
160      * packet by another n bytes. The packet will be in the sub-array of
161      * s->rlayer.rbuf.buf specified by s->rlayer.packet and
162      * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
163      * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
164      * if clearold == 1, move the packet to the start of the buffer; if
165      * clearold == 0 then leave any old packets where they were
166      */
167     size_t len, left, align = 0;
168     unsigned char *pkt;
169     SSL3_BUFFER *rb;
170
171     if (n == 0)
172         return OSSL_RECORD_RETURN_NON_FATAL_ERR;
173
174     rb = &rl->rbuf;
175     /*
176      * TODO(RECLAYER): Once this function is only called from inside the rlayer
177      * directly, we can probably remove this since it is initialised in
178      * tls_get_more_records
179      */
180     if (rb->buf == NULL) {
181         if (!rlayer_setup_read_buffer(rl)) {
182             /* RLAYERfatal() already called */
183             return OSSL_RECORD_RETURN_FATAL;
184         }
185     }
186
187     left = rb->left;
188 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
189     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
190     align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
191 #endif
192
193     if (!extend) {
194         /* start with empty packet ... */
195         if (left == 0) {
196             rb->offset = align;
197         } else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
198             /*
199              * check if next packet length is large enough to justify payload
200              * alignment...
201              */
202             pkt = rb->buf + rb->offset;
203             if (pkt[0] == SSL3_RT_APPLICATION_DATA
204                     && (pkt[3] << 8 | pkt[4]) >= 128) {
205                 /*
206                  * Note that even if packet is corrupted and its length field
207                  * is insane, we can only be led to wrong decision about
208                  * whether memmove will occur or not. Header values has no
209                  * effect on memmove arguments and therefore no buffer
210                  * overrun can be triggered.
211                  */
212                 memmove(rb->buf + align, pkt, left);
213                 rb->offset = align;
214             }
215         }
216         rl->packet = rb->buf + rb->offset;
217         rl->packet_length = 0;
218         /* ... now we can act as if 'extend' was set */
219     }
220
221     len = rl->packet_length;
222     pkt = rb->buf + align;
223     /*
224      * Move any available bytes to front of buffer: 'len' bytes already
225      * pointed to by 'packet', 'left' extra ones at the end
226      */
227     if (rl->packet != pkt && clearold == 1) {
228         memmove(pkt, rl->packet, len + left);
229         rl->packet = pkt;
230         rb->offset = len + align;
231     }
232
233     /*
234      * For DTLS/UDP reads should not span multiple packets because the read
235      * operation returns the whole packet at once (as long as it fits into
236      * the buffer).
237      */
238     if (rl->isdtls) {
239         if (left == 0 && extend)
240             return 0;
241         if (left > 0 && n > left)
242             n = left;
243     }
244
245     /* if there is enough in the buffer from a previous read, take some */
246     if (left >= n) {
247         rl->packet_length += n;
248         rb->left = left - n;
249         rb->offset += n;
250         *readbytes = n;
251         return OSSL_RECORD_RETURN_SUCCESS;
252     }
253
254     /* else we need to read more data */
255
256     if (n > rb->len - rb->offset) {
257         /* does not happen */
258         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
259         return OSSL_RECORD_RETURN_FATAL;
260     }
261
262     /* We always act like read_ahead is set for DTLS */
263     if (!rl->read_ahead && !rl->isdtls) {
264         /* ignore max parameter */
265         max = n;
266     } else {
267         if (max < n)
268             max = n;
269         if (max > rb->len - rb->offset)
270             max = rb->len - rb->offset;
271     }
272
273     while (left < n) {
274         size_t bioread = 0;
275         int ret;
276         BIO *bio = rl->prev != NULL ? rl->prev : rl->bio;
277
278         /*
279          * Now we have len+left bytes at the front of s->s3.rbuf.buf and
280          * need to read in more until we have len+n (up to len+max if
281          * possible)
282          */
283
284         clear_sys_error();
285         if (bio != NULL) {
286             ret = BIO_read(bio, pkt + len + left, max - left);
287             if (ret > 0) {
288                 bioread = ret;
289                 ret = OSSL_RECORD_RETURN_SUCCESS;
290             } else if (BIO_should_retry(bio)) {
291                 if (rl->prev != NULL) {
292                     /*
293                      * We were reading from the previous epoch. Now there is no
294                      * more data, so swap to the actual transport BIO
295                      */
296                     BIO_free(rl->prev);
297                     rl->prev = NULL;
298                     continue;
299                 }
300                 ret = OSSL_RECORD_RETURN_RETRY;
301             } else if (BIO_eof(bio)) {
302                 ret = OSSL_RECORD_RETURN_EOF;
303             } else {
304                 ret = OSSL_RECORD_RETURN_FATAL;
305             }
306         } else {
307             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
308             ret = OSSL_RECORD_RETURN_FATAL;
309         }
310
311         if (ret <= OSSL_RECORD_RETURN_RETRY) {
312             rb->left = left;
313             if (rl->mode & SSL_MODE_RELEASE_BUFFERS && !rl->isdtls)
314                 if (len + left == 0)
315                     rlayer_release_read_buffer(rl);
316             return ret;
317         }
318         left += bioread;
319         /*
320          * reads should *never* span multiple packets for DTLS because the
321          * underlying transport protocol is message oriented as opposed to
322          * byte oriented as in the TLS case.
323          */
324         if (rl->isdtls) {
325             if (n > left)
326                 n = left;       /* makes the while condition false */
327         }
328     }
329
330     /* done reading, now the book-keeping */
331     rb->offset += n;
332     rb->left = left - n;
333     rl->packet_length += n;
334     *readbytes = n;
335     return OSSL_RECORD_RETURN_SUCCESS;
336 }
337
338 /*
339  * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
340  * for us in the buffer.
341  */
342 static int tls_record_app_data_waiting(OSSL_RECORD_LAYER *rl)
343 {
344     SSL3_BUFFER *rbuf;
345     size_t left, len;
346     unsigned char *p;
347
348     rbuf = &rl->rbuf;
349
350     p = SSL3_BUFFER_get_buf(rbuf);
351     if (p == NULL)
352         return 0;
353
354     left = SSL3_BUFFER_get_left(rbuf);
355
356     if (left < SSL3_RT_HEADER_LENGTH)
357         return 0;
358
359     p += SSL3_BUFFER_get_offset(rbuf);
360
361     /*
362      * We only check the type and record length, we will sanity check version
363      * etc later
364      */
365     if (*p != SSL3_RT_APPLICATION_DATA)
366         return 0;
367
368     p += 3;
369     n2s(p, len);
370
371     if (left < SSL3_RT_HEADER_LENGTH + len)
372         return 0;
373
374     return 1;
375 }
376
377 static int rlayer_early_data_count_ok(OSSL_RECORD_LAYER *rl, size_t length,
378                                       size_t overhead, int send)
379 {
380     uint32_t max_early_data = rl->max_early_data;
381
382     if (max_early_data == 0) {
383         RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
384                  SSL_R_TOO_MUCH_EARLY_DATA);
385         return 0;
386     }
387
388     /* If we are dealing with ciphertext we need to allow for the overhead */
389     max_early_data += overhead;
390
391     if (rl->early_data_count + length > max_early_data) {
392         RLAYERfatal(rl, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
393                  SSL_R_TOO_MUCH_EARLY_DATA);
394         return 0;
395     }
396     rl->early_data_count += length;
397
398     return 1;
399 }
400
401 /*
402  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
403  * will be processed per call to ssl3_get_record. Without this limit an
404  * attacker could send empty records at a faster rate than we can process and
405  * cause ssl3_get_record to loop forever.
406  */
407 #define MAX_EMPTY_RECORDS 32
408
409 #define SSL2_RT_HEADER_LENGTH   2
410
411 /*-
412  * Call this to buffer new input records in rl->rrec.
413  * It will return a OSSL_RECORD_RETURN_* value.
414  * When it finishes successfully (OSSL_RECORD_RETURN_SUCCESS), |rl->num_recs|
415  * records have been decoded. For each record 'i':
416  * rrec[i].type    - is the type of record
417  * rrec[i].data,   - data
418  * rrec[i].length, - number of bytes
419  * Multiple records will only be returned if the record types are all
420  * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
421  * |max_pipelines|
422  */
423 int tls_get_more_records(OSSL_RECORD_LAYER *rl)
424 {
425     int enc_err, rret;
426     int i;
427     size_t more, n;
428     SSL3_RECORD *rr, *thisrr;
429     SSL3_BUFFER *rbuf;
430     unsigned char *p;
431     unsigned char md[EVP_MAX_MD_SIZE];
432     unsigned int version;
433     size_t mac_size = 0;
434     int imac_size;
435     size_t num_recs = 0, max_recs, j;
436     PACKET pkt, sslv2pkt;
437     SSL_MAC_BUF *macbufs = NULL;
438     int ret = OSSL_RECORD_RETURN_FATAL;
439
440     rr = rl->rrec;
441     rbuf = &rl->rbuf;
442     if (rbuf->buf == NULL) {
443         if (!rlayer_setup_read_buffer(rl)) {
444             /* RLAYERfatal() already called */
445             return OSSL_RECORD_RETURN_FATAL;
446         }
447     }
448
449     max_recs = rl->max_pipelines;
450
451     if (max_recs == 0)
452         max_recs = 1;
453
454     do {
455         thisrr = &rr[num_recs];
456
457         /* check if we have the header */
458         if ((rl->rstate != SSL_ST_READ_BODY) ||
459             (rl->packet_length < SSL3_RT_HEADER_LENGTH)) {
460             size_t sslv2len;
461             unsigned int type;
462
463             rret = rl->funcs->read_n(rl, SSL3_RT_HEADER_LENGTH,
464                                      SSL3_BUFFER_get_len(rbuf), 0,
465                                      num_recs == 0 ? 1 : 0, &n);
466
467             if (rret < OSSL_RECORD_RETURN_SUCCESS)
468                 return rret; /* error or non-blocking */
469
470             rl->rstate = SSL_ST_READ_BODY;
471
472             p = rl->packet;
473             if (!PACKET_buf_init(&pkt, p, rl->packet_length)) {
474                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
475                 return OSSL_RECORD_RETURN_FATAL;
476             }
477             sslv2pkt = pkt;
478             if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
479                     || !PACKET_get_1(&sslv2pkt, &type)) {
480                 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
481                 return OSSL_RECORD_RETURN_FATAL;
482             }
483             /*
484              * The first record received by the server may be a V2ClientHello.
485              */
486             if (rl->role == OSSL_RECORD_ROLE_SERVER
487                     && rl->is_first_record
488                     && (sslv2len & 0x8000) != 0
489                     && (type == SSL2_MT_CLIENT_HELLO)) {
490                 /*
491                  *  SSLv2 style record
492                  *
493                  * |num_recs| here will actually always be 0 because
494                  * |num_recs > 0| only ever occurs when we are processing
495                  * multiple app data records - which we know isn't the case here
496                  * because it is an SSLv2ClientHello. We keep it using
497                  * |num_recs| for the sake of consistency
498                  */
499                 thisrr->type = SSL3_RT_HANDSHAKE;
500                 thisrr->rec_version = SSL2_VERSION;
501
502                 thisrr->length = sslv2len & 0x7fff;
503
504                 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
505                     - SSL2_RT_HEADER_LENGTH) {
506                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
507                                 SSL_R_PACKET_LENGTH_TOO_LONG);
508                     return OSSL_RECORD_RETURN_FATAL;
509                 }
510             } else {
511                 /* SSLv3+ style record */
512
513                 /* Pull apart the header into the SSL3_RECORD */
514                 if (!PACKET_get_1(&pkt, &type)
515                         || !PACKET_get_net_2(&pkt, &version)
516                         || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
517                     rl->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, rl->cbarg);
518                     RLAYERfatal(rl, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
519                     return OSSL_RECORD_RETURN_FATAL;
520                 }
521                 thisrr->type = type;
522                 thisrr->rec_version = version;
523
524                 /*
525                  * When we call validate_record_header() only records actually
526                  * received in SSLv2 format should have the record version set
527                  * to SSL2_VERSION. This way validate_record_header() can know
528                  * what format the record was in based on the version.
529                  */
530                 if (thisrr->rec_version == SSL2_VERSION) {
531                     RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION,
532                                 SSL_R_WRONG_VERSION_NUMBER);
533                     return OSSL_RECORD_RETURN_FATAL;
534                 }
535
536                 rl->msg_callback(0, version, SSL3_RT_HEADER, p, 5, rl->cbarg);
537
538                 if (thisrr->length >
539                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
540                     RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
541                                 SSL_R_PACKET_LENGTH_TOO_LONG);
542                     return OSSL_RECORD_RETURN_FATAL;
543                 }
544             }
545
546             if (!rl->funcs->validate_record_header(rl, thisrr)) {
547                 /* RLAYERfatal already called */
548                 return OSSL_RECORD_RETURN_FATAL;
549             }
550
551             /* now rl->rstate == SSL_ST_READ_BODY */
552         }
553
554         /*
555          * rl->rstate == SSL_ST_READ_BODY, get and decode the data. Calculate
556          * how much more data we need to read for the rest of the record
557          */
558         if (thisrr->rec_version == SSL2_VERSION) {
559             more = thisrr->length + SSL2_RT_HEADER_LENGTH
560                 - SSL3_RT_HEADER_LENGTH;
561         } else {
562             more = thisrr->length;
563         }
564
565         if (more > 0) {
566             /* now rl->packet_length == SSL3_RT_HEADER_LENGTH */
567
568             rret = rl->funcs->read_n(rl, more, more, 1, 0, &n);
569             if (rret < OSSL_RECORD_RETURN_SUCCESS)
570                 return rret;     /* error or non-blocking io */
571         }
572
573         /* set state for later operations */
574         rl->rstate = SSL_ST_READ_HEADER;
575
576         /*
577          * At this point, rl->packet_length == SSL3_RT_HEADER_LENGTH
578          * + thisrr->length, or rl->packet_length == SSL2_RT_HEADER_LENGTH
579          * + thisrr->length and we have that many bytes in rl->packet
580          */
581         if (thisrr->rec_version == SSL2_VERSION)
582             thisrr->input = &(rl->packet[SSL2_RT_HEADER_LENGTH]);
583         else
584             thisrr->input = &(rl->packet[SSL3_RT_HEADER_LENGTH]);
585
586         /*
587          * ok, we can now read from 'rl->packet' data into 'thisrr'.
588          * thisrr->input points at thisrr->length bytes, which need to be copied
589          * into thisrr->data by either the decryption or by the decompression.
590          * When the data is 'copied' into the thisrr->data buffer,
591          * thisrr->input will be updated to point at the new buffer
592          */
593
594         /*
595          * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
596          * thisrr->length bytes of encrypted compressed stuff.
597          */
598
599         /* decrypt in place in 'thisrr->input' */
600         thisrr->data = thisrr->input;
601         thisrr->orig_len = thisrr->length;
602
603         /* Mark this record as not read by upper layers yet */
604         thisrr->read = 0;
605
606         num_recs++;
607
608         /* we have pulled in a full packet so zero things */
609         rl->packet_length = 0;
610         rl->is_first_record = 0;
611     } while (num_recs < max_recs
612              && thisrr->type == SSL3_RT_APPLICATION_DATA
613              && RLAYER_USE_EXPLICIT_IV(rl)
614              && rl->enc_ctx != NULL
615              && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(rl->enc_ctx))
616                  & EVP_CIPH_FLAG_PIPELINE) != 0
617              && tls_record_app_data_waiting(rl));
618
619     if (num_recs == 1
620             && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
621                /* The following can happen in tlsany_meth after HRR */
622             && rl->version == TLS1_3_VERSION
623             && rl->is_first_handshake) {
624         /*
625          * CCS messages must be exactly 1 byte long, containing the value 0x01
626          */
627         if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
628             RLAYERfatal(rl, SSL_AD_ILLEGAL_PARAMETER,
629                         SSL_R_INVALID_CCS_MESSAGE);
630             return OSSL_RECORD_RETURN_FATAL;
631         }
632         /*
633          * CCS messages are ignored in TLSv1.3. We treat it like an empty
634          * handshake record
635          */
636         thisrr->type = SSL3_RT_HANDSHAKE;
637         if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
638             RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE,
639                         SSL_R_UNEXPECTED_CCS_MESSAGE);
640             return OSSL_RECORD_RETURN_FATAL;
641         }
642         thisrr->read = 1;
643         rl->num_recs = 0;
644         rl->curr_rec = 0;
645         rl->num_released = 0;
646
647         return OSSL_RECORD_RETURN_SUCCESS;
648     }
649
650     if (rl->md_ctx != NULL) {
651         const EVP_MD *tmpmd = EVP_MD_CTX_get0_md(rl->md_ctx);
652
653         if (tmpmd != NULL) {
654             imac_size = EVP_MD_get_size(tmpmd);
655             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
656                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
657                     return OSSL_RECORD_RETURN_FATAL;
658             }
659             mac_size = (size_t)imac_size;
660         }
661     }
662
663     /*
664      * If in encrypt-then-mac mode calculate mac from encrypted record. All
665      * the details below are public so no timing details can leak.
666      */
667     if (rl->use_etm && rl->md_ctx) {
668         unsigned char *mac;
669
670         for (j = 0; j < num_recs; j++) {
671             thisrr = &rr[j];
672
673             if (thisrr->length < mac_size) {
674                 RLAYERfatal(rl, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
675                 return OSSL_RECORD_RETURN_FATAL;
676             }
677             thisrr->length -= mac_size;
678             mac = thisrr->data + thisrr->length;
679             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
680             if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
681                 RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
682                             SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
683                 return OSSL_RECORD_RETURN_FATAL;
684             }
685         }
686         /*
687          * We've handled the mac now - there is no MAC inside the encrypted
688          * record
689          */
690         mac_size = 0;
691     }
692
693     if (mac_size > 0) {
694         macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
695         if (macbufs == NULL) {
696             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
697             return OSSL_RECORD_RETURN_FATAL;
698         }
699     }
700
701     enc_err = rl->funcs->cipher(rl, rr, num_recs, 0, macbufs, mac_size);
702
703     /*-
704      * enc_err is:
705      *    0: if the record is publicly invalid, or an internal error, or AEAD
706      *       decryption failed, or ETM decryption failed.
707      *    1: Success or MTE decryption failed (MAC will be randomised)
708      */
709     if (enc_err == 0) {
710         if (rl->alert != 0) {
711             /* RLAYERfatal() already got called */
712             goto end;
713         }
714         if (num_recs == 1 && rl->skip_early_data(rl->cbarg)) {
715             /*
716              * Valid early_data that we cannot decrypt will fail here. We treat
717              * it like an empty record.
718              */
719
720             thisrr = &rr[0];
721
722             if (!rlayer_early_data_count_ok(rl, thisrr->length,
723                                             EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
724                 /* RLAYERfatal() already called */
725                 goto end;
726             }
727
728             thisrr->length = 0;
729             thisrr->read = 1;
730             rl->num_recs = 0;
731             rl->curr_rec = 0;
732             rl->num_released = 0;
733             /* Reset the read sequence */
734             memset(rl->sequence, 0, sizeof(rl->sequence));
735             ret = 1;
736             goto end;
737         }
738         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
739                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
740         goto end;
741     }
742     OSSL_TRACE_BEGIN(TLS) {
743         BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
744         BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
745     } OSSL_TRACE_END(TLS);
746
747     /* r->length is now the compressed data plus mac */
748     if (rl->enc_ctx != NULL
749             && !rl->use_etm
750             && EVP_MD_CTX_get0_md(rl->md_ctx) != NULL) {
751         /* rl->md_ctx != NULL => mac_size != -1 */
752
753         for (j = 0; j < num_recs; j++) {
754             SSL_MAC_BUF *thismb = &macbufs[j];
755             thisrr = &rr[j];
756
757             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
758             if (i == 0 || thismb == NULL || thismb->mac == NULL
759                 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
760                 enc_err = 0;
761             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
762                 enc_err = 0;
763         }
764     }
765
766     if (enc_err == 0) {
767         if (rl->alert != 0) {
768             /* We already called RLAYERfatal() */
769             goto end;
770         }
771         /*
772          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
773          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
774          * failure is directly visible from the ciphertext anyway, we should
775          * not reveal which kind of error occurred -- this might become
776          * visible to an attacker (e.g. via a logfile)
777          */
778         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
779                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
780         goto end;
781     }
782
783     for (j = 0; j < num_recs; j++) {
784         thisrr = &rr[j];
785
786         if (!rl->funcs->post_process_record(rl, thisrr)) {
787             /* RLAYERfatal already called */
788             goto end;
789         }
790
791         /*
792          * Check if the received packet overflows the current
793          * Max Fragment Length setting.
794          * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
795          */
796         if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
797             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
798             goto end;
799         }
800
801         thisrr->off = 0;
802         /*-
803          * So at this point the following is true
804          * thisrr->type   is the type of record
805          * thisrr->length == number of bytes in record
806          * thisrr->off    == offset to first valid byte
807          * thisrr->data   == where to take bytes from, increment after use :-).
808          */
809
810         /* just read a 0 length packet */
811         if (thisrr->length == 0) {
812             if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
813                 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
814                 goto end;
815             }
816         } else {
817             rl->empty_record_count = 0;
818         }
819     }
820
821     if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
822         thisrr = &rr[0];
823         if (thisrr->type == SSL3_RT_APPLICATION_DATA
824                 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
825             /* RLAYERfatal already called */
826             goto end;
827         }
828     }
829
830     rl->num_recs = num_recs;
831     rl->curr_rec = 0;
832     rl->num_released = 0;
833     ret = OSSL_RECORD_RETURN_SUCCESS;
834  end:
835     if (macbufs != NULL) {
836         for (j = 0; j < num_recs; j++) {
837             if (macbufs[j].alloced)
838                 OPENSSL_free(macbufs[j].mac);
839         }
840         OPENSSL_free(macbufs);
841     }
842     return ret;
843 }
844
845 /* Shared by ssl3_meth and tls1_meth */
846 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
847 {
848     size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
849
850     if (rec->rec_version != rl->version) {
851         RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
852         return 0;
853     }
854
855 #ifndef OPENSSL_NO_COMP
856     /*
857         * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
858         * does not include the compression overhead anyway.
859         */
860     if (rl->expand == NULL)
861         len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
862 #endif
863
864     if (rec->length > len) {
865         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
866                     SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
867         return 0;
868     }
869
870     return 1;
871 }
872
873 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
874 {
875 #ifndef OPENSSL_NO_COMP
876     int i;
877
878     if (rec->comp == NULL) {
879         rec->comp = (unsigned char *)
880             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
881     }
882     if (rec->comp == NULL)
883         return 0;
884
885     i = COMP_expand_block(rl->expand, rec->comp,
886                           SSL3_RT_MAX_PLAIN_LENGTH, rec->data, (int)rec->length);
887     if (i < 0)
888         return 0;
889     else
890         rec->length = i;
891     rec->data = rec->comp;
892     return 1;
893 #else
894     return 0;
895 #endif
896 }
897
898 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
899 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
900 {
901     if (rl->expand != NULL) {
902         if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
903             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
904                         SSL_R_COMPRESSED_LENGTH_TOO_LONG);
905             return 0;
906         }
907         if (!tls_do_uncompress(rl, rec)) {
908             RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
909                         SSL_R_BAD_DECOMPRESSION);
910             return 0;
911         }
912     }
913
914     if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
915         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
916         return 0;
917     }
918
919     return 1;
920 }
921
922 /* Shared by tls13_meth and ktls_meth */
923 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
924 {
925     if (rec->type != SSL3_RT_APPLICATION_DATA
926             && rec->type != SSL3_RT_ALERT
927             && rec->type != SSL3_RT_HANDSHAKE) {
928         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
929         return 0;
930     }
931
932     rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
933                         1, rl->cbarg);
934
935     /*
936      * TLSv1.3 alert and handshake records are required to be non-zero in
937      * length.
938      */
939     if ((rec->type == SSL3_RT_HANDSHAKE
940                 || rec->type == SSL3_RT_ALERT)
941             && rec->length == 0) {
942         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
943         return 0;
944     }
945
946     return 1;
947 }
948
949 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,  int *rversion,
950                     int *type, unsigned char **data, size_t *datalen,
951                     uint16_t *epoch, unsigned char *seq_num)
952 {
953     SSL3_RECORD *rec;
954
955     /*
956      * tls_get_more_records() can return success without actually reading
957      * anything useful (i.e. if empty records are read). We loop here until
958      * we have something useful. tls_get_more_records() will eventually fail if
959      * too many sequential empty records are read.
960      */
961     while (rl->curr_rec >= rl->num_recs) {
962         int ret;
963
964         if (rl->num_released != rl->num_recs) {
965             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
966             return OSSL_RECORD_RETURN_FATAL;
967         }
968
969         ret = rl->funcs->get_more_records(rl);
970
971         if (ret != OSSL_RECORD_RETURN_SUCCESS)
972             return ret;
973     }
974
975     /*
976      * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
977      * points to the next one to read.
978      */
979     rec = &rl->rrec[rl->curr_rec++];
980
981     *rechandle = rec;
982     *rversion = rec->rec_version;
983     *type = rec->type;
984     *data = rec->data + rec->off;
985     *datalen = rec->length;
986     if (rl->isdtls) {
987         *epoch = (uint16_t)rec->epoch;
988         memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
989     }
990
991     return OSSL_RECORD_RETURN_SUCCESS;
992 }
993
994 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
995 {
996     if (!ossl_assert(rl->num_released < rl->curr_rec)
997             || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
998         /* Should not happen */
999         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
1000         return OSSL_RECORD_RETURN_FATAL;
1001     }
1002
1003     rl->num_released++;
1004
1005     return OSSL_RECORD_RETURN_SUCCESS;
1006 }
1007
1008 int
1009 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1010                          int role, int direction, int level, unsigned char *key,
1011                          size_t keylen, unsigned char *iv, size_t ivlen,
1012                          unsigned char *mackey, size_t mackeylen,
1013                          const EVP_CIPHER *ciph, size_t taglen,
1014                          int mactype,
1015                          const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1016                          BIO *transport, BIO *next, BIO_ADDR *local,
1017                          BIO_ADDR *peer, const OSSL_PARAM *settings,
1018                          const OSSL_PARAM *options,
1019                          const OSSL_DISPATCH *fns, void *cbarg,
1020                          OSSL_RECORD_LAYER **retrl)
1021 {
1022     OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1023     const OSSL_PARAM *p;
1024
1025     *retrl = NULL;
1026
1027     if (rl == NULL) {
1028         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1029         return OSSL_RECORD_RETURN_FATAL;
1030     }
1031
1032     /*
1033      * TODO(RECLAYER): Need to handle the case where the params are updated
1034      * after the record layer has been created.
1035      */
1036     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
1037     if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1038         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1039         goto err;
1040     }
1041
1042     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1043     if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1044         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1045         goto err;
1046     }
1047
1048     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1049     if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1050         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1051         goto err;
1052     }
1053
1054     /* Loop through all the settings since they must all be understood */
1055     for (p = settings; p->key != NULL; p++) {
1056         if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1057             if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1058                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1059                 goto err;
1060             }
1061         } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1062             if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1063                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1064                 goto err;
1065             }
1066         } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1067             if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1068                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1069                 goto err;
1070             }
1071         } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1072             if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1073                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1074                 goto err;
1075             }
1076         } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1077             if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1078                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1079                 goto err;
1080             }
1081         } else {
1082             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1083             goto err;
1084         }
1085     }
1086
1087
1088     if (level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1089         /*
1090          * We ignore any read_ahead setting prior to the application protection
1091          * level. Otherwise we may read ahead data in a lower protection level
1092          * that is destined for a higher protection level. To simplify the logic
1093          * we don't support that at this stage.
1094          */
1095         /*
1096          * TODO(RECLAYER): Handle the case of read_ahead at the application
1097          * level and a key update/reneg occurs.
1098          */
1099         p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1100         if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1101             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1102             goto err;
1103         }
1104     }
1105
1106     rl->libctx = libctx;
1107     rl->propq = propq;
1108
1109     rl->version = vers;
1110     rl->role = role;
1111     rl->direction = direction;
1112     rl->level = level;
1113
1114     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1115         rl->is_first_record = 1;
1116
1117     if (!tls_set1_bio(rl, transport))
1118         goto err;
1119
1120     if (prev != NULL && !BIO_up_ref(prev))
1121         goto err;
1122     rl->prev = prev;
1123
1124     if (next != NULL && !BIO_up_ref(next))
1125         goto err;
1126     rl->next = next;
1127
1128     rl->cbarg = cbarg;
1129     for (; fns->function_id != 0; fns++) {
1130         switch (fns->function_id) {
1131         case OSSL_FUNC_RLAYER_SKIP_EARLY_DATA:
1132             rl->skip_early_data = OSSL_FUNC_rlayer_skip_early_data(fns);
1133             break;
1134         case OSSL_FUNC_RLAYER_MSG_CALLBACK:
1135             rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
1136             break;
1137         case OSSL_FUNC_RLAYER_SECURITY:
1138             rl->security = OSSL_FUNC_rlayer_security(fns);
1139             break;
1140         default:
1141             /* Just ignore anything we don't understand */
1142             break;
1143         }
1144     }
1145
1146     *retrl = rl;
1147     return OSSL_RECORD_RETURN_SUCCESS;
1148  err:
1149     tls_int_free(rl);
1150     return OSSL_RECORD_RETURN_FATAL;
1151 }
1152
1153 static int
1154 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1155                      int role, int direction, int level, unsigned int epoch,
1156                      unsigned char *key, size_t keylen, unsigned char *iv,
1157                      size_t ivlen, unsigned char *mackey, size_t mackeylen,
1158                      const EVP_CIPHER *ciph, size_t taglen,
1159                      int mactype,
1160                      const EVP_MD *md, const SSL_COMP *comp, BIO *prev, 
1161                      BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1162                      const OSSL_PARAM *settings, const OSSL_PARAM *options,
1163                      const OSSL_DISPATCH *fns, void *cbarg,
1164                      OSSL_RECORD_LAYER **retrl)
1165 {
1166     int ret;
1167     
1168     ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1169                                    key, keylen, iv, ivlen, mackey, mackeylen,
1170                                    ciph, taglen, mactype, md, comp, prev,
1171                                    transport, next, local, peer, settings,
1172                                    options, fns, cbarg, retrl);
1173
1174     if (ret != OSSL_RECORD_RETURN_SUCCESS)
1175         return ret;
1176
1177     switch (vers) {
1178     case TLS_ANY_VERSION:
1179         (*retrl)->funcs = &tls_any_funcs;
1180         break;
1181     case TLS1_3_VERSION:
1182         (*retrl)->funcs = &tls_1_3_funcs;
1183         break;
1184     case TLS1_2_VERSION:
1185     case TLS1_1_VERSION:
1186     case TLS1_VERSION:
1187         (*retrl)->funcs = &tls_1_funcs;
1188         break;
1189     case SSL3_VERSION:
1190         (*retrl)->funcs = &ssl_3_0_funcs;
1191         break;
1192     default:
1193         /* Should not happen */
1194         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1195         ret = OSSL_RECORD_RETURN_FATAL;
1196         goto err;
1197     }
1198
1199     ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1200                                              ivlen, mackey, mackeylen, ciph,
1201                                              taglen, mactype, md, comp);
1202
1203  err:
1204     if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1205         OPENSSL_free(*retrl);
1206         *retrl = NULL;
1207     }
1208     return ret;
1209 }
1210
1211 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1212 {
1213     /* TODO(RECLAYER): Cleanse sensitive fields */
1214     BIO_free(rl->prev);
1215     BIO_free(rl->bio);
1216     BIO_free(rl->next);
1217     SSL3_BUFFER_release(&rl->rbuf);
1218
1219     EVP_CIPHER_CTX_free(rl->enc_ctx);
1220     EVP_MD_CTX_free(rl->md_ctx);
1221 #ifndef OPENSSL_NO_COMP
1222     COMP_CTX_free(rl->expand);
1223 #endif
1224
1225     OPENSSL_free(rl);
1226 }
1227
1228 int tls_free(OSSL_RECORD_LAYER *rl)
1229 {
1230     SSL3_BUFFER *rbuf;
1231     size_t left, written;
1232     int ret = 1;
1233
1234     rbuf = &rl->rbuf;
1235
1236     left = SSL3_BUFFER_get_left(rbuf);
1237     if (left > 0) {
1238         /*
1239          * This record layer is closing but we still have data left in our
1240          * buffer. It must be destined for the next epoch - so push it there.
1241          */
1242         ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1243     }
1244     tls_int_free(rl);
1245
1246     return ret;
1247 }
1248
1249
1250 int tls_reset(OSSL_RECORD_LAYER *rl)
1251 {
1252     memset(rl, 0, sizeof(*rl));
1253     return 1;
1254 }
1255
1256 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1257 {
1258     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1259 }
1260
1261 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1262 {
1263     return rl->curr_rec < rl->num_recs;
1264 }
1265
1266 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1267 {
1268     size_t i;
1269     size_t num = 0;
1270
1271     for (i = rl->curr_rec; i <rl->num_recs; i++) {
1272         if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1273             return num;
1274         num += rl->rrec[i].length;
1275     }
1276     return num;
1277 }
1278
1279 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1280 {
1281     return 0;
1282 }
1283
1284 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1285 {
1286     return 0;
1287 }
1288
1289 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1290 {
1291     return 0;
1292 }
1293
1294 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE **templates,
1295                       size_t numtempl, size_t allowance, size_t *sent)
1296 {
1297     return 0;
1298 }
1299
1300 int tls_retry_write_records(OSSL_RECORD_LAYER *rl, size_t allowance,
1301                             size_t *sent)
1302 {
1303     return 0;
1304 }
1305
1306
1307 int tls_get_alert_code(OSSL_RECORD_LAYER *rl)
1308 {
1309     return rl->alert;
1310 }
1311
1312 int tls_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
1313 {
1314     if (bio != NULL && !BIO_up_ref(bio))
1315         return 0;
1316     BIO_free(rl->bio);
1317     rl->bio = bio;
1318
1319     return 1;
1320 }
1321
1322 /* Shared by most methods except tlsany_meth */
1323 int tls_default_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1324 {
1325     if (rl->version != version)
1326         return 0;
1327
1328     return 1;
1329 }
1330
1331 int tls_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
1332 {
1333     return rl->funcs->set_protocol_version(rl, version);
1334 }
1335
1336 void tls_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
1337 {
1338     rl->allow_plain_alerts = allow;
1339 }
1340
1341 void tls_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
1342 {
1343     rl->is_first_handshake = first;
1344 }
1345
1346 void tls_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
1347 {
1348     rl->max_pipelines = max_pipelines;
1349     if (max_pipelines > 1)
1350         rl->read_ahead = 1;
1351 }
1352
1353 const OSSL_RECORD_METHOD ossl_tls_record_method = {
1354     tls_new_record_layer,
1355     tls_free,
1356     tls_reset,
1357     tls_unprocessed_read_pending,
1358     tls_processed_read_pending,
1359     tls_app_data_pending,
1360     tls_write_pending,
1361     tls_get_max_record_len,
1362     tls_get_max_records,
1363     tls_write_records,
1364     tls_retry_write_records,
1365     tls_read_record,
1366     tls_release_record,
1367     tls_get_alert_code,
1368     tls_set1_bio,
1369     tls_set_protocol_version,
1370     tls_set_plain_alerts,
1371     tls_set_first_handshake,
1372     tls_set_max_pipelines,
1373     NULL
1374 };