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