Remove redefinition of SSL_AD_NO_ALERT
[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)
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 s->s3.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 ssl3_get_record. Without this limit an
390  * attacker could send empty records at a faster rate than we can process and
391  * cause ssl3_get_record 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             thisrr = &rr[j];
737
738             i = rl->funcs->mac(rl, thisrr, md, 0 /* not send */);
739             if (i == 0 || thismb == NULL || thismb->mac == NULL
740                 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
741                 enc_err = 0;
742             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
743                 enc_err = 0;
744         }
745     }
746
747     if (enc_err == 0) {
748         if (rl->alert != SSL_AD_NO_ALERT) {
749             /* We already called RLAYERfatal() */
750             goto end;
751         }
752         /*
753          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
754          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
755          * failure is directly visible from the ciphertext anyway, we should
756          * not reveal which kind of error occurred -- this might become
757          * visible to an attacker (e.g. via a logfile)
758          */
759         RLAYERfatal(rl, SSL_AD_BAD_RECORD_MAC,
760                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
761         goto end;
762     }
763
764     for (j = 0; j < num_recs; j++) {
765         thisrr = &rr[j];
766
767         if (!rl->funcs->post_process_record(rl, thisrr)) {
768             /* RLAYERfatal already called */
769             goto end;
770         }
771
772         /*
773          * Check if the received packet overflows the current
774          * Max Fragment Length setting.
775          * Note: rl->max_frag_len > 0 and KTLS are mutually exclusive.
776          */
777         if (rl->max_frag_len > 0 && thisrr->length > rl->max_frag_len) {
778             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
779             goto end;
780         }
781
782         thisrr->off = 0;
783         /*-
784          * So at this point the following is true
785          * thisrr->type   is the type of record
786          * thisrr->length == number of bytes in record
787          * thisrr->off    == offset to first valid byte
788          * thisrr->data   == where to take bytes from, increment after use :-).
789          */
790
791         /* just read a 0 length packet */
792         if (thisrr->length == 0) {
793             if (++(rl->empty_record_count) > MAX_EMPTY_RECORDS) {
794                 RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_RECORD_TOO_SMALL);
795                 goto end;
796             }
797         } else {
798             rl->empty_record_count = 0;
799         }
800     }
801
802     if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_EARLY) {
803         thisrr = &rr[0];
804         if (thisrr->type == SSL3_RT_APPLICATION_DATA
805                 && !rlayer_early_data_count_ok(rl, thisrr->length, 0, 0)) {
806             /* RLAYERfatal already called */
807             goto end;
808         }
809     }
810
811     rl->num_recs = num_recs;
812     rl->curr_rec = 0;
813     rl->num_released = 0;
814     ret = OSSL_RECORD_RETURN_SUCCESS;
815  end:
816     if (macbufs != NULL) {
817         for (j = 0; j < num_recs; j++) {
818             if (macbufs[j].alloced)
819                 OPENSSL_free(macbufs[j].mac);
820         }
821         OPENSSL_free(macbufs);
822     }
823     return ret;
824 }
825
826 /* Shared by ssl3_meth and tls1_meth */
827 int tls_default_validate_record_header(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
828 {
829     size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
830
831     if (rec->rec_version != rl->version) {
832         RLAYERfatal(rl, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_VERSION_NUMBER);
833         return 0;
834     }
835
836 #ifndef OPENSSL_NO_COMP
837     /*
838         * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
839         * does not include the compression overhead anyway.
840         */
841     if (rl->expand == NULL)
842         len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
843 #endif
844
845     if (rec->length > len) {
846         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
847                     SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
848         return 0;
849     }
850
851     return 1;
852 }
853
854 int tls_do_uncompress(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
855 {
856 #ifndef OPENSSL_NO_COMP
857     int i;
858
859     if (rec->comp == NULL) {
860         rec->comp = (unsigned char *)
861             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
862     }
863     if (rec->comp == NULL)
864         return 0;
865
866     i = COMP_expand_block(rl->expand, rec->comp,
867                           SSL3_RT_MAX_PLAIN_LENGTH, rec->data, (int)rec->length);
868     if (i < 0)
869         return 0;
870     else
871         rec->length = i;
872     rec->data = rec->comp;
873     return 1;
874 #else
875     return 0;
876 #endif
877 }
878
879 /* Shared by tlsany_meth, ssl3_meth and tls1_meth */
880 int tls_default_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
881 {
882     if (rl->expand != NULL) {
883         if (rec->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
884             RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW,
885                         SSL_R_COMPRESSED_LENGTH_TOO_LONG);
886             return 0;
887         }
888         if (!tls_do_uncompress(rl, rec)) {
889             RLAYERfatal(rl, SSL_AD_DECOMPRESSION_FAILURE,
890                         SSL_R_BAD_DECOMPRESSION);
891             return 0;
892         }
893     }
894
895     if (rec->length > SSL3_RT_MAX_PLAIN_LENGTH) {
896         RLAYERfatal(rl, SSL_AD_RECORD_OVERFLOW, SSL_R_DATA_LENGTH_TOO_LONG);
897         return 0;
898     }
899
900     return 1;
901 }
902
903 /* Shared by tls13_meth and ktls_meth */
904 int tls13_common_post_process_record(OSSL_RECORD_LAYER *rl, SSL3_RECORD *rec)
905 {
906     if (rec->type != SSL3_RT_APPLICATION_DATA
907             && rec->type != SSL3_RT_ALERT
908             && rec->type != SSL3_RT_HANDSHAKE) {
909         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_RECORD_TYPE);
910         return 0;
911     }
912
913     rl->msg_callback(0, rl->version, SSL3_RT_INNER_CONTENT_TYPE, &rec->type,
914                         1, rl->cbarg);
915
916     /*
917      * TLSv1.3 alert and handshake records are required to be non-zero in
918      * length.
919      */
920     if ((rec->type == SSL3_RT_HANDSHAKE
921                 || rec->type == SSL3_RT_ALERT)
922             && rec->length == 0) {
923         RLAYERfatal(rl, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_BAD_LENGTH);
924         return 0;
925     }
926
927     return 1;
928 }
929
930 int tls_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,  int *rversion,
931                     int *type, unsigned char **data, size_t *datalen,
932                     uint16_t *epoch, unsigned char *seq_num)
933 {
934     SSL3_RECORD *rec;
935
936     /*
937      * tls_get_more_records() can return success without actually reading
938      * anything useful (i.e. if empty records are read). We loop here until
939      * we have something useful. tls_get_more_records() will eventually fail if
940      * too many sequential empty records are read.
941      */
942     while (rl->curr_rec >= rl->num_recs) {
943         int ret;
944
945         if (rl->num_released != rl->num_recs) {
946             RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_RECORDS_NOT_RELEASED);
947             return OSSL_RECORD_RETURN_FATAL;
948         }
949
950         ret = rl->funcs->get_more_records(rl);
951
952         if (ret != OSSL_RECORD_RETURN_SUCCESS)
953             return ret;
954     }
955
956     /*
957      * We have now got rl->num_recs records buffered in rl->rrec. rl->curr_rec
958      * points to the next one to read.
959      */
960     rec = &rl->rrec[rl->curr_rec++];
961
962     *rechandle = rec;
963     *rversion = rec->rec_version;
964     *type = rec->type;
965     *data = rec->data + rec->off;
966     *datalen = rec->length;
967     if (rl->isdtls) {
968         *epoch = rec->epoch;
969         memcpy(seq_num, rec->seq_num, sizeof(rec->seq_num));
970     }
971
972     return OSSL_RECORD_RETURN_SUCCESS;
973 }
974
975 int tls_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
976 {
977     if (!ossl_assert(rl->num_released < rl->curr_rec)
978             || !ossl_assert(rechandle == &rl->rrec[rl->num_released])) {
979         /* Should not happen */
980         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_INVALID_RECORD);
981         return OSSL_RECORD_RETURN_FATAL;
982     }
983
984     rl->num_released++;
985
986     if (rl->curr_rec == rl->num_released
987             && (rl->mode & SSL_MODE_RELEASE_BUFFERS) != 0
988             && SSL3_BUFFER_get_left(&rl->rbuf) == 0)
989         tls_release_read_buffer(rl);
990
991     return OSSL_RECORD_RETURN_SUCCESS;
992 }
993
994 int tls_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
995 {
996     const OSSL_PARAM *p;
997
998     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_OPTIONS);
999     if (p != NULL && !OSSL_PARAM_get_uint64(p, &rl->options)) {
1000         ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1001         return 0;
1002     }
1003
1004     p = OSSL_PARAM_locate_const(options, OSSL_LIBSSL_RECORD_LAYER_PARAM_MODE);
1005     if (p != NULL && !OSSL_PARAM_get_uint32(p, &rl->mode)) {
1006         ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1007         return 0;
1008     }
1009
1010     p = OSSL_PARAM_locate_const(options,
1011                                 OSSL_LIBSSL_RECORD_LAYER_READ_BUFFER_LEN);
1012     if (p != NULL && !OSSL_PARAM_get_size_t(p, &rl->rbuf.default_len)) {
1013         ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1014         return 0;
1015     }
1016
1017     if (rl->level == OSSL_RECORD_PROTECTION_LEVEL_APPLICATION) {
1018         /*
1019          * We ignore any read_ahead setting prior to the application protection
1020          * level. Otherwise we may read ahead data in a lower protection level
1021          * that is destined for a higher protection level. To simplify the logic
1022          * we don't support that at this stage.
1023          */
1024         p = OSSL_PARAM_locate_const(options,
1025                                     OSSL_LIBSSL_RECORD_LAYER_PARAM_READ_AHEAD);
1026         if (p != NULL && !OSSL_PARAM_get_int(p, &rl->read_ahead)) {
1027             ERR_raise(ERR_LIB_SSL, SSL_R_FAILED_TO_GET_PARAMETER);
1028             return 0;
1029         }
1030     }
1031
1032     return 1;
1033 }
1034
1035 int
1036 tls_int_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1037                          int role, int direction, int level, unsigned char *key,
1038                          size_t keylen, unsigned char *iv, size_t ivlen,
1039                          unsigned char *mackey, size_t mackeylen,
1040                          const EVP_CIPHER *ciph, size_t taglen,
1041                          int mactype,
1042                          const EVP_MD *md, const SSL_COMP *comp, BIO *prev,
1043                          BIO *transport, BIO *next, BIO_ADDR *local,
1044                          BIO_ADDR *peer, const OSSL_PARAM *settings,
1045                          const OSSL_PARAM *options,
1046                          const OSSL_DISPATCH *fns, void *cbarg,
1047                          OSSL_RECORD_LAYER **retrl)
1048 {
1049     OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
1050     const OSSL_PARAM *p;
1051
1052     *retrl = NULL;
1053
1054     if (rl == NULL) {
1055         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
1056         return OSSL_RECORD_RETURN_FATAL;
1057     }
1058
1059     /* Loop through all the settings since they must all be understood */
1060     if (settings != NULL) {
1061         for (p = settings; p->key != NULL; p++) {
1062             if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_USE_ETM) == 0) {
1063                 if (!OSSL_PARAM_get_int(p, &rl->use_etm)) {
1064                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1065                                 SSL_R_FAILED_TO_GET_PARAMETER);
1066                     goto err;
1067                 }
1068             } else if (strcmp(p->key,
1069                               OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_FRAG_LEN) == 0) {
1070                 if (!OSSL_PARAM_get_uint(p, &rl->max_frag_len)) {
1071                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1072                                 SSL_R_FAILED_TO_GET_PARAMETER);
1073                     goto err;
1074                 }
1075             } else if (strcmp(p->key,
1076                               OSSL_LIBSSL_RECORD_LAYER_PARAM_MAX_EARLY_DATA) == 0) {
1077                 if (!OSSL_PARAM_get_uint32(p, &rl->max_early_data)) {
1078                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1079                                 SSL_R_FAILED_TO_GET_PARAMETER);
1080                     goto err;
1081                 }
1082             } else if (strcmp(p->key,
1083                               OSSL_LIBSSL_RECORD_LAYER_PARAM_STREAM_MAC) == 0) {
1084                 if (!OSSL_PARAM_get_int(p, &rl->stream_mac)) {
1085                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1086                                 SSL_R_FAILED_TO_GET_PARAMETER);
1087                     goto err;
1088                 }
1089             } else if (strcmp(p->key, OSSL_LIBSSL_RECORD_LAYER_PARAM_TLSTREE) == 0) {
1090                 if (!OSSL_PARAM_get_int(p, &rl->tlstree)) {
1091                     RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1092                                 SSL_R_FAILED_TO_GET_PARAMETER);
1093                     goto err;
1094                 }
1095             } else {
1096                 RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR,
1097                             SSL_R_UNKNOWN_MANDATORY_PARAMETER);
1098                 goto err;
1099             }
1100         }
1101     }
1102
1103     rl->libctx = libctx;
1104     rl->propq = propq;
1105
1106     rl->version = vers;
1107     rl->role = role;
1108     rl->direction = direction;
1109     rl->level = level;
1110
1111     rl->alert = SSL_AD_NO_ALERT;
1112
1113     if (level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
1114         rl->is_first_record = 1;
1115
1116     if (!tls_set1_bio(rl, transport))
1117         goto err;
1118
1119     if (prev != NULL && !BIO_up_ref(prev))
1120         goto err;
1121     rl->prev = prev;
1122
1123     if (next != NULL && !BIO_up_ref(next))
1124         goto err;
1125     rl->next = next;
1126
1127     rl->cbarg = cbarg;
1128     if (fns != NULL) {
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
1147     if (!tls_set_options(rl, options)) {
1148         RLAYERfatal(rl, SSL_AD_INTERNAL_ERROR, SSL_R_FAILED_TO_GET_PARAMETER);
1149         goto err;
1150     }
1151
1152     *retrl = rl;
1153     return OSSL_RECORD_RETURN_SUCCESS;
1154  err:
1155     tls_int_free(rl);
1156     return OSSL_RECORD_RETURN_FATAL;
1157 }
1158
1159 static int
1160 tls_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
1161                      int role, int direction, int level, uint16_t epoch,
1162                      unsigned char *key, size_t keylen, unsigned char *iv,
1163                      size_t ivlen, unsigned char *mackey, size_t mackeylen,
1164                      const EVP_CIPHER *ciph, size_t taglen,
1165                      int mactype,
1166                      const EVP_MD *md, const SSL_COMP *comp, BIO *prev, 
1167                      BIO *transport, BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
1168                      const OSSL_PARAM *settings, const OSSL_PARAM *options,
1169                      const OSSL_DISPATCH *fns, void *cbarg,
1170                      OSSL_RECORD_LAYER **retrl)
1171 {
1172     int ret;
1173     
1174     ret = tls_int_new_record_layer(libctx, propq, vers, role, direction, level,
1175                                    key, keylen, iv, ivlen, mackey, mackeylen,
1176                                    ciph, taglen, mactype, md, comp, prev,
1177                                    transport, next, local, peer, settings,
1178                                    options, fns, cbarg, retrl);
1179
1180     if (ret != OSSL_RECORD_RETURN_SUCCESS)
1181         return ret;
1182
1183     switch (vers) {
1184     case TLS_ANY_VERSION:
1185         (*retrl)->funcs = &tls_any_funcs;
1186         break;
1187     case TLS1_3_VERSION:
1188         (*retrl)->funcs = &tls_1_3_funcs;
1189         break;
1190     case TLS1_2_VERSION:
1191     case TLS1_1_VERSION:
1192     case TLS1_VERSION:
1193         (*retrl)->funcs = &tls_1_funcs;
1194         break;
1195     case SSL3_VERSION:
1196         (*retrl)->funcs = &ssl_3_0_funcs;
1197         break;
1198     default:
1199         /* Should not happen */
1200         ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1201         ret = OSSL_RECORD_RETURN_FATAL;
1202         goto err;
1203     }
1204
1205     ret = (*retrl)->funcs->set_crypto_state(*retrl, level, key, keylen, iv,
1206                                              ivlen, mackey, mackeylen, ciph,
1207                                              taglen, mactype, md, comp);
1208
1209  err:
1210     if (ret != OSSL_RECORD_RETURN_SUCCESS) {
1211         OPENSSL_free(*retrl);
1212         *retrl = NULL;
1213     }
1214     return ret;
1215 }
1216
1217 static void tls_int_free(OSSL_RECORD_LAYER *rl)
1218 {
1219     BIO_free(rl->prev);
1220     BIO_free(rl->bio);
1221     BIO_free(rl->next);
1222     SSL3_BUFFER_release(&rl->rbuf);
1223
1224     EVP_CIPHER_CTX_free(rl->enc_ctx);
1225     EVP_MD_CTX_free(rl->md_ctx);
1226 #ifndef OPENSSL_NO_COMP
1227     COMP_CTX_free(rl->expand);
1228 #endif
1229
1230     if (rl->version == SSL3_VERSION)
1231         OPENSSL_cleanse(rl->mac_secret, sizeof(rl->mac_secret));
1232
1233     OPENSSL_free(rl);
1234 }
1235
1236 int tls_free(OSSL_RECORD_LAYER *rl)
1237 {
1238     SSL3_BUFFER *rbuf;
1239     size_t left, written;
1240     int ret = 1;
1241
1242     rbuf = &rl->rbuf;
1243
1244     left = SSL3_BUFFER_get_left(rbuf);
1245     if (left > 0) {
1246         /*
1247          * This record layer is closing but we still have data left in our
1248          * buffer. It must be destined for the next epoch - so push it there.
1249          */
1250         ret = BIO_write_ex(rl->next, rbuf->buf + rbuf->offset, left, &written);
1251     }
1252     tls_int_free(rl);
1253
1254     return ret;
1255 }
1256
1257
1258 int tls_reset(OSSL_RECORD_LAYER *rl)
1259 {
1260     memset(rl, 0, sizeof(*rl));
1261     return 1;
1262 }
1263
1264 int tls_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
1265 {
1266     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
1267 }
1268
1269 int tls_processed_read_pending(OSSL_RECORD_LAYER *rl)
1270 {
1271     return rl->curr_rec < rl->num_recs;
1272 }
1273
1274 size_t tls_app_data_pending(OSSL_RECORD_LAYER *rl)
1275 {
1276     size_t i;
1277     size_t num = 0;
1278
1279     for (i = rl->curr_rec; i <rl->num_recs; i++) {
1280         if (rl->rrec[i].type != SSL3_RT_APPLICATION_DATA)
1281             return num;
1282         num += rl->rrec[i].length;
1283     }
1284     return num;
1285 }
1286
1287 int tls_write_pending(OSSL_RECORD_LAYER *rl)
1288 {
1289     return 0;
1290 }
1291
1292 size_t tls_get_max_record_len(OSSL_RECORD_LAYER *rl)
1293 {
1294     return 0;
1295 }
1296
1297 size_t tls_get_max_records(OSSL_RECORD_LAYER *rl)
1298 {
1299     return 0;
1300 }
1301
1302 int tls_write_records(OSSL_RECORD_LAYER *rl, OSSL_RECORD_TEMPLATE **templates,
1303                       size_t numtempl, size_t allowance, size_t *sent)
1304 {
1305     return 0;
1306 }
1307
1308 int tls_retry_write_records(OSSL_RECORD_LAYER *rl, size_t allowance,
1309                             size_t *sent)
1310 {
1311     return 0;
1312 }
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     switch (rl->rstate) {
1366     case SSL_ST_READ_HEADER:
1367         shrt = "RH";
1368         lng = "read header";
1369         break;
1370     case SSL_ST_READ_BODY:
1371         shrt = "RB";
1372         lng = "read body";
1373         break;
1374     default:
1375         shrt = lng = "unknown";
1376         break;
1377     }
1378     if (shortstr != NULL)
1379         *shortstr = shrt;
1380     if (longstr != NULL)
1381         *longstr = lng;
1382 }
1383
1384 const OSSL_RECORD_METHOD ossl_tls_record_method = {
1385     tls_new_record_layer,
1386     tls_free,
1387     tls_reset,
1388     tls_unprocessed_read_pending,
1389     tls_processed_read_pending,
1390     tls_app_data_pending,
1391     tls_write_pending,
1392     tls_get_max_record_len,
1393     tls_get_max_records,
1394     tls_write_records,
1395     tls_retry_write_records,
1396     tls_read_record,
1397     tls_release_record,
1398     tls_get_alert_code,
1399     tls_set1_bio,
1400     tls_set_protocol_version,
1401     tls_set_plain_alerts,
1402     tls_set_first_handshake,
1403     tls_set_max_pipelines,
1404     NULL,
1405     tls_get_state,
1406     tls_set_options
1407 };