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