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