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